public class ReduceToOneDigit { public static void main(String[] args) { long x=123456789; // call the method several times to demonstrate using different length long values System.out.println("Reducing " + x + " to one digit gives us " + reduce(x)); x=357; System.out.println("Reducing " + x + " to one digit gives us " + reduce(x)); x=9999; System.out.println("Reducing " + x + " to one digit gives us " + reduce(x)); x=3525154; System.out.println("Reducing " + x + " to one digit gives us " + reduce(x)); x=9876985498999911l; System.out.println("Reducing " + x + " to one digit gives us " + reduce(x)); } public static long reduce(long x) { if(x<=9) return x; // if x is a single digit (<=9) return it else return reduce(x%10+x/10); // otherwise return the result of calling reduce by adding the rightmost digit (x%10) and the // rest of the number (x/10) } // example: x=12345, reduce(12345) = reduce(1+2345) = reduce (1 + 2 + 345) = reduce (1 + 2 + 3 + 45) = reduce (1 + 2 + 3 + 4 + 5) // = reduce (15) = reduce (1 + 5) = reduce(6) = 6 }