Sum of the number until it's become single digit in java

Now It's a 50th post. Here after it's should be increase, I hope.

Requirement:
If you're entered number is 123456

1+2+3+4+5+6 = 21 (Two Digit)

2+1 = 3 (Single Digit)

So, we need the single digit.

Here is the solution,

public class DigitSum {

    public static int calculateSum(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }

    public static int result(int n) {
        while (n > 9) {
            n = calculateSum(n);
        }
        return n;
    }

    public static void main(String[] arg) {
        System.out.println(result(123456));
    }
}

Comments

Popular posts from this blog

Clear the app data programmatically in android

convert an integer to a string in java

Print the large string values in android log cat.