Java Program Challenge: Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example:

Input: 38

Output: 2

Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.

Since 2 has only one digit, return it.

Java Program:

public class number {
    public static void main(String[] args) {
       int sum = addDigits(38);
        System.out.println(sum);
    }

    public static int addDigits(int num) {
        if (num==0){
            return 0;
        }
        return num%9==0 ?9:num%9;

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *