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));
}
}
Sol: Sum of the numbers formed by taking all the given n digits is ( sum of all the n digits ) x (n-1) !
What is digit sum? We can obtain the sum of digits by adding the digits of a number by ignoring the place values. So, for example, if we have the number 567 , we can calculate the digit sum as 5 + 6 + 7 , which will give us 18 .
Hence the correct answer is (C) 16×3!
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 :
public int sumDigit(int n){
return (n%9 == 0 && n != 0) ? 9 : n%9;
}
Alternate implementation :
public int sumDigit(int n){
int sum = n % 9;
if(sum == 0){
if(n > 0)
return 9;
}
return sum;
}
What you are looking for is digital root. So here's a better solution using the formula from wiki
page I linked.
Without Recursion: -
public static int compute( int n ) {
return n - 9 * ((n - 1) / 9);
}
And, just in case you want (Which I don't think you would), here's a one-liner (Using Recursion): -
public static int compute( int n ) {
return n < 10 ? n : compute(n % 10 + compute(n / 10));
}
public int FindSumDigit(int number)
{
if (number < 10) return number;
int sum = 0;
while (number > 0)
{
sum += number % 10;
number = number / 10;
}
return FindSumDigit(sum);
}
Find my code... Poon you were not adding the whole digits.. In middle itself u was keep on adding the right most digit.
Many wrong answers here. Here's what OP wants:
Method return should be like if entered a number, suppose 345, then output should be 3+4+5=12 --> 1+2 = 3.
This will do the job:
public static int compute(int param) {
int sum = 0;
do {
sum = 0;
while (param > 0) {
sum += param % 10;
param /= 10;
}
param = sum;
} while (sum >= 10);
return sum;
}
I changed your method to this, then it gives the requested result:
public int compute(int methParam) {
int sum = 0;
for (int i = 0; methParam > 10; i++) {
int currentDigit = methParam % 10;
methParam = methParam / 10;
sum = sum + currentDigit;
}
if (sum + methParam > 10) {
return compute(sum + methParam);
} else {
return sum + methParam;
}
}
Please note that i moved the declaration of sum
inside the method, instead of making it a field.
IN your code your are not properly returning values to get call for your recursion method.
if ((MethParam >= 10)){
return compute(MethParam);
}else
return Sum + MethParam;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With