Simple
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class SimpleSum{ public static void main(String args[]){ int Int = 475849; int temp = Int; int sum=0; while(temp!=0){ sum += temp%10; temp /= 10; } System.out.println("Sum of Digits is " + sum); } } |
Recursive
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class RecurSum{ private int Int = 475849; private int recursiveSum(int x){ if(x==0) return 0; int sum = recursiveSum(x/10) + x%10; return sum; } public void example(){ System.out.println(recursiveSum(Int)); } } |