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,

Note: integer have some certain limits, use long or BigInt if entered number is very big.

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

Flutter Bloc - Clean Architecture

What's new in android 14?

Dependencies vs Dev Dependencies in Flutter