Recursive Digit Sum

  • + 0 comments

    Java 8 solution. Passed all cases. Make sure you are storing the sum of the digits as a Long.

        public static int superDigit(String n, int k) {
        // Write your code here
    
            if (n.length() == 1){
                return Integer.parseInt(n);
                
            }
            
            else{
                long sum = 0;
                for (int i = 0; i < n.length(); i++){
                    sum += n.charAt(i) - '0';
                }
                sum = sum * k;
                return superDigit(Long.toString(sum), 1);
            }
            
        }