Recursive Digit Sum

  • + 5 comments

    python3 solution passed.

    def superDigit(n, k):
        
        def add_digits(string):
            if len(string) == 1:
                return string
            result = sum(int(s) for s in string)
            return add_digits(str(result))
        
        start = sum(int(s) for s in n) * k
        return add_digits(str(start))
    
    • + 0 comments

      Really nice code. Thank you.

    • + 1 comment

      Does this really work?

      • + 0 comments

        Yes, this solution uses recursion and also does not need the % 9 trick. You can show to yourself that "k" can be multiplied after summing up n by using the problem statement example, n = 9875, and change k from 1 to 5. You'll see that the solutions are multiples of one another, except for when it is 10 (which results in having to sum up the integers)

        Also, you can simplify this answer further, so as not to have a "start" variable:

            def superDigit(n, k):
                    sd = sum(int(s) for s in n)
                    if sd*k < 10:
                            return sd*k
                    else:
                            return superDigit(str(sd*k), 1)
        
    • + 1 comment
      [deleted]