There is an arithmetic solution to this problem, without converting to a string. It's probably what the string conversion does internally and will therefore likely be much more efficient.
Quoting Wikipedia:
The digit sum of a number \$x\$ in base \$b\$ is given by
$$
\sum_{n=0}^{\lfloor \log_b x\rfloor} \frac{1}{b^n}(x \bmod b^{n + 1} - x \bmod b^n).
$$
This StackOverflow answer has an implementation in C# (which is very similar to Java):
sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
In addition, I'd like to comment on the naming of your method. In my opinion, digit
doesn't describe its function very well. Instead I'd recommend something similar to digitSum
.
Note that this approach doesn't handle negative numbers. They cause the function to go into an infinite loop. To handle that case, you can something like the following:
public static int digitSum(int n) {
int sum = 0;
bool isNegative = false;
if (n < 0) {
isNegative = true;
n *= -1;
}
while (n != 0) {
sum += n % 10;
n /= 10;
}
if (isNegative) {
return -sum;
} else {
return sum;
}
}