Iterative |
Recursive |
public static long
sumOfDigits(long x) { long sum = 0; while (x > 0) { sum += x%10; x = x/10; } return sum; } |
public static long
sumOfDigits(long x) { if (x < 10) { return x; } return (x % 10) + sumOfDigits( x / 10 ); } (Notice: No "sum" variable) |