H.Ing - 5 months ago 50

Java Question

How can I make the following allow negative numbers and treats them as positives. Ex. -91 = 10

It currently works for taking int n and adding all digits, but just for positives. Thanks!

`public static int sumOfDigits(int n) {`

int sum = 0;

while (n > 0) {

sum += n % 10;

n = n / 10;

}

return sum;

}

Answer

Simple solution: add `n = Math.abs(n)`

as the first line of the function. This solution works for all numbers, except Integer.MIN_VALUE.

Always correct solution: replace loop condition by `n != 0`

and return `Math.abs(sum)`

as the result.