Recursive Digit Sum

Sort by

recency

|

595 Discussions

|

  • + 0 comments

    Python solution:

    def superDigit(n: str, k: int) -> int:
        # sum digits of 'n' first and then multiply by k, 
        # instead of summing up digits of int(string * k):
        p = sum(list(map(int, list(n)))) * k
        while p > 10:     # same as len(str(p)) != 1
            p = sum(list(map(int, list(str(p)))))
            # can also use sum(int(digit) for digit in str(p))
        return p
    
  • + 0 comments

    Python 3 solution

    Initially I tried expanding the string n by k multiple:

    full_integer = n * k
    

    This lead to runtime error in 4 hidden cases.

    Instead, summing all digits in n then multiplying by k solves the runtime issue.

    def int_to_int_arr(integer):
        return list(map(int, str(integer)))
    
    def sum_array(n):
        if len(n) != 1:
            new_int = sum(n)
            int_arr = int_to_int_arr(new_int)
            return sum_array(int_arr)
        else:
            # One digit left in integer
            return n[0]
    
    def superDigit(n, k):
        # Cast n string to int array
        int_arr = list(map(int, n))
        
        # Multiply sum by k
        sum_multiple = sum(int_arr) * k
        
        # Cast sum multiple to int array
        int_arr = int_to_int_arr(sum_multiple)
        return sum_array(int_arr)
    
  • + 0 comments

    Modern solution using java 8 streams:

        Long sum = 0L;        
    
        for (char digit : n.toCharArray()) {            
            sum += Character.getNumericValue(digit) * k;            
        }
    
        while(sum.toString().length() > 1) {
    
            List<String> remainingDigits= String.valueOf(sum)
                                                .chars()
                                                .mapToObj(c -> String.valueOf((char) c))
                                                .collect(Collectors.toList());
    
            sum = remainingDigits.stream().mapToLong(Long::parseLong).reduce(0L, Long::sum);
    
        }       
    
        return sum.intValue();   
    
    }
    
  • + 0 comments

    Agree with others that the description isn't very clear in regards to what k is used for. Had to work it out from the failed test cases.

  • + 2 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.