Recursive Digit Sum

  • + 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); 
    }
    

    `