Recursive Digit Sum

Sort by

recency

|

615 Discussions

|

  • + 0 comments

    This problem can be solved mathematically. The result is a "digital root." Before beginning the usual calculations, it's necessary to prepare for them:

        public static int superDigit(String n, int k) {
            long sum = 0;
            for (int i = 0; i < n.length(); i++) { //optimising first value
                sum+= n.charAt(i) - '0'; //'0' - because n.charAt(i) - returns ASCII code instead value itself
            }
            sum*=k; //Multiplication after a single calculation
            return Math.toIntExact(1 + ((sum - 1) % 9));
        }
    

    If we don't need to calculate huge values like n=861568688536788, k=100000, we can use a simple calculation:

    1 + (Integer.parseInt(n.repeat(k)) - 1) % 9; // String.repeat since Java 11
    

    However, both options are not entirely suitable, since they do not solve the problem head-on, through a loop and recursion.

  • + 0 comments

    wrong tests

  • + 1 comment

    Can confirm - tests are wrong: one glaring example: 123 = 1+2+3 = 6. Test expects that to be 9. Hackerrank is enterprise software confirmed.

  • + 0 comments

    For anyone struggling with the last test case and getting overflow: you might have to use a 64-bit integer to hold the super digit value, even if you choose to return a 32-bit integer at the end:

    int superDigit(string n, int k) {
        if(n.size() == 1 && k == 1) return stoi(n);
        long super_digit = 0;
        for(char c : n){
            int current = c - '0';
            super_digit += current;
        }
        super_digit *= k;
        return superDigit(to_string(super_digit), 1);
    }
    
  • + 0 comments

    setting the n constraint to 10^100000 is pure evil lol