I have to build a method to add every digit of a string given in parameter and so till there are only 1 digit left, e.g. 1234 = (1+2+3+4) = 10 = (1+0) = 1
.
At first, I thought a recursive call or a while loop should be fine. But Is there a smarter way? Using the modulo perhaps?
1234 % 9 = 1
That's seems to work... But no: 9%9
is not equal to 9
but it is to 0
.
Is there a way to build this function without recursive/for/ while?
I have found the simple algorithm somewhere not long a time ago. Actually with it works with %9
, however you have to check the case if the modulo of that number is equal 0
.
I bet there would exist more ways to reach the result, the simplest code would in Java like this:
int sumAllDigits(int n) {
return (n%9 == 0 && n!=0) ? 9 : n%9;
}
int sumAllDigits(int n) {
return (n-1)%9 + 1;
}
Works for all n >= 1
x%9
actually does work. The only hitch is when you get 0, you don't know if you should have gotten 0 or 9. But you can look back at your original number for that: the only thing that can return 0 is 0. So:
public int digitSum(int input) {
if ( input == 0 ) {
return 0;
}
int ret = input % 9;
if ( ret == 0 ) {
return 9;
}
return ret;
}
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