Method return should be like if entered a number, suppose 345, then output should be 3+4+5=12 –> 1+2 = 3. what i am doing wrong here?
public class DigitSum
{
int Sum=0;
public int compute( int MethParam )
{
int rem = MethParam%10;
Sum+=rem;
MethParam = MethParam/10;
if(MethParam>10)
compute(MethParam);
return Sum+MethParam;
}
public static void main(String[] args)
{
DigitSum ds = new DigitSum();
System.out.println(ds.compute(435));
}
}
O(1) Algo for sum Of digits :
Taking the modulo 9 of any number will return the sum of digits of that number until a single digit number is obtained.
If the number is a multiple of 9, then the sum will will be 9
one liner :
Alternate implementation :