Java – the sum of all numbers for a given positive number
•
Java
Method returns that if you enter a number, assuming 345, the output should be 3 4 5 = 12 – > 1 2 = 3 What did I do 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));
}
}
Solution
O (1) algo is the sum of numbers:
Taking the modulus 9 of any number will return the sum of the numbers of that number until a single number is obtained
If the number is a multiple of 9, the sum will be 9
One liner:
public int sumDigit(int n){
return (n%9 == 0 && n != 0) ? 9 : n%9;
}
Alternative implementation:
public int sumDigit(int n){
int sum = n % 9;
if(sum == 0){
if(n > 0)
return 9;
}
return sum;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
