Recursive Digit Sum

Sort by

recency

|

609 Discussions

|

  • + 0 comments

    Tests are not even correct.

  • + 1 comment

    I think the test are broken. I'm getting the results that match the sample, while the test results do not match the sample.

  • + 0 comments

    Scala Solution ` def superDigit(n: String, k: Int): Int = { var num = (n.map(.asDigit).sum.toLong * k).toString while (num.length > 1){ num = num.map(.asDigit).sum.toString } num.toInt

    }
    

    }

    object Solution { def main(args: Array[String]): Unit = {

       val input = StdIn.readLine().split(" ")
       val n = input(0)
       val k = input(1).toInt
       val result = Result.superDigit(n, k)
       println(result)
    }
    

    } `

  • + 0 comments

    You can solve this mathematically in Python with:

    result = (int(n) * int(k)) % 9
    return result if result != 0 else 9
    

    However, if n is a very long number, int(n) may raise a ValueError due to the digit limit introduced in recent Python versions. You can bypass this by increasing the limit:

    import sys
    sys.set_int_max_str_digits(100000)
    

    Use with caution, especially when handling untrusted input, as increasing the limit can expose your code to denial-of-service risks.

    Reference: Python Docs – Integer string conversion length limitation

  • + 0 comments

    If you're having trouble with timeouts or the last 3 cases:

    1. Don't try to build a string of len(n) * k length or try to implement a loop over the string repeatedly - just calculate the sum of the digits of n then multiply by k
    2. If you fail cases 5, 7, 8 after that, make sure your integer type is at least 64 bits as the values for those cases overflow 32 bit integers (even though the setup for languages like golang always want 32 bit answers)