Recursive Digit Sum

Sort by

recency

|

810 Discussions

|

  • + 0 comments

    Python one-liner with recursion:

    return n if k == 1 and n < 10 else superDigit(k * sum(int(d) for d in list(str(n))), 1)

  • + 0 comments

    Typescript Solution

       if (n.length === 1) {
            return +n;
        }
        let sum: number = n.split('')
        .reduce((a, b) => { 
            return +a + +b 
        }, 0);    
        sum *= k;
        
        return superDigit(sum.toString(), 1) ;
    
  • + 0 comments

    def superDigit(n, k): # Calculate the initial sum for the repeated number num = str(sum(map(int, str(n))) * k)

    # Define the helper function for finding the super digit
    while len(num) > 1:
        num = str(sum(map(int, num)))
    
    return int(num)
    
  • + 0 comments

    `//Java solution with recursion:-

    public static int superDigit(String n, int k) { if(n.length()==1) return Integer.parseInt(n);

    long sum = 0;
    int i =0;
    int[] digitArr = new int[n.length()];
    
    while(i<n.length()){
        digitArr[i]=Integer.parseInt(n.charAt(i)+"");
        i++;
    }
    
    for(int j=0; j<digitArr.length;j++){
        if(digitArr[j]!=0)
            sum+=digitArr[j]*k;
    }
    //Calling the function recursively with n = String value of sum 
    // and k = 1 as there is no repition required
    return superDigit(String.valueOf(sum), 1); 
    }
    

    `

  • + 1 comment

    There is no recursion here, checkout my 3 line solution:

    public static int superDigit(String n, int k) {
            BigInteger num=new BigInteger(n);
            int rem=  num.remainder(new BigInteger("9")).multiply(new BigInteger(k+"")).intValue();
       
        return rem%9==0?9: rem%9;
        }