Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add digit of number [duplicate]

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?

like image 990
Charly Roch Avatar asked Apr 14 '16 13:04

Charly Roch


Video Answer


3 Answers

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;
}
like image 143
Nikolas Charalambidis Avatar answered Oct 06 '22 00:10

Nikolas Charalambidis


int sumAllDigits(int n) {
    return (n-1)%9 + 1;
}

Works for all n >= 1

like image 25
MS Srikkanth Avatar answered Oct 05 '22 22:10

MS Srikkanth


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;
}
like image 43
Teepeemm Avatar answered Oct 05 '22 23:10

Teepeemm