Recursive Digit Sum

Sort by

recency

|

603 Discussions

|

  • + 0 comments
    def superDigit(n, k):
        sum1=sum(int(i) for i in  n)
        sum2=sum1*k
        while sum2>=10:
            sum2=sum(int(i) for i in str(sum2))
        return sum2
    
  • + 1 comment

    148, 3

    1+4+8 = 13 1+3 = 4 4+0 = 4

    Wrong Result = 4 Correct Result = 3

    Bug

    • + 0 comments

      You should multiply this string n by k. So it is gonna be "148148148" not just "148". So basically (1+4+8) * 3 = 39 => 3+9=12 => 1+2 = 3

  • + 0 comments

    Here is my solution to this problem in Java

    public static int superDigit(String n, int k) {
            if(n.length() == 1){
                return Integer.parseInt(n);
            }
            
            long sum = n.chars().mapToLong(x -> Integer.parseInt(Character.toString(x))).sum() * k;
            
            return superDigit(Long.toString(sum), 1);
        }
    
  • + 1 comment

    My code seems to work in Eclipse but it turns wrong in the test cases

    public static int superDigit(String n, int k) {
    	    // Write your code here
    	        BigInteger superDigit = new BigInteger(n);
    	        StringBuilder sb = new StringBuilder();
    	        for (int i = 0; i < k; i++) {
    	            sb.append(n);
    	        }
    	        n = sb.toString();
    	        char[] superDigitCharArray;
    	        while(superDigit.compareTo(new BigInteger("10")) != -1){
    	            int sum = 0;
    	            superDigitCharArray = n.toCharArray();
    	            for (char c : superDigitCharArray) {
    	                sum += Character.getNumericValue(c); 
    	            }
    	            superDigit = new BigInteger(sum + "");
    	            n = superDigit + "";
    	        }
    	        
    
    	        return superDigit.intValue();
    	    }
    
    • + 0 comments

      I see it now, you are supposed to make it with recursion.

  • + 2 comments

    The test cases don't seem to work or am I missing something? Input (stdin) 148 3 Your Output (stdout) 4 (which is correct - 1+4+8 = 13, 1+3 =4) Expected Output 3

    • + 0 comments

      Agreed. So many problems here have incorrect test cases that are either just flat out wrong, or don't match the written requirements.

    • + 1 comment

      no it is true, 148 3 means 148148148 sum of its digits is 39. 39 -> 3 + 9=12. 12->1+2=3.

      • + 0 comments

        Thank you, didn't read it well enough...