Fastest method for adding/summing the individual digit components of a number

后端 未结 4 658
无人及你
无人及你 2021-02-03 10:53

I saw a question on a math forum a while back where a person was discussing adding up the digits in a number over and over again until a single digit is achieved. (i.e. \"362\"

4条回答
  •  萌比男神i
    2021-02-03 11:01

    For short code, try this:

    int digit_sum(int n){
        if (n<10) return n;
        return n%10 + digit_sum(n/10);
    }
    

    Or, in words,

    -If the number is less than ten, then the digit sum is the number itself.

    -Otherwise, the digit sum is the current last digit (a.k.a. n mod10 or n%10), plus the digit sum of everything to the left of that number (n divided by 10, using integer division).

    -This algorithm can also be generalized for any base, substituting the base in for 10.

提交回复
热议问题