Recursive Digit Sum

Sort by

recency

|

591 Discussions

|

  • + 0 comments

    go is unfortunately pretty badly supported here.

    My code produces a Runtime Error just for test cases 7,8,9, while the exact same code produces correct output on my machine (for case 7:the expected 7).

    It's also suspicious that a Runtime Error happens only for a certain case...usually it's a real problem or not. :(( hackerrank these are things wanting to move me away to other platforms.

  • + 0 comments

    def superDigit(n, k): str1 = str(n) sum1 = 0 for char in str1: sum1 += int(char) sum1 = k*sum1 while True: str2 = str(sum1) sum1 = 0 for char in str2: sum1 += int(char) if sum1 < 10: break return sum1

  • + 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);
            }
            
        }
    
  • + 1 comment

    I guess test cases 0, 10 and 11 are not well designed, since they expect an output of 3 for an input of 148, an output of 8 for an input of 875, and an output of 9 for an input of 123. I am working with Swift.

  • + 0 comments

    php solution:

    function superDigit($n, $k) {
        // Write your code here
        if(strlen($n) == 1 && $k <= 1)
            return $n;
            
        $sum = 0;
        
        for($i = 0; $i < strlen($n); $i++)
            $sum += (int) $n[$i] * $k;
        
        return superDigit((string)$sum, 1);
    }