Recursive Digit Sum

Sort by

recency

|

811 Discussions

|

  • + 0 comments

    c# solution with recursion :

    if(n.Length == 1){
    	return int.Parse(n);
    }
    
    //Loop trough the digits and multiply by k, the convert to string again
    n = (n.Sum(c => char.GetNumericValue(c))*k).ToString();
    return superDigit(n,1);
    
  • + 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); 
    }
    

    `