H.Ing H.Ing - 1 year ago 90
Java Question

Sum of digits (INC. Negative numbers)

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download