What's the fastest and easiest to read implementation of calculating the sum of digits?
I.e. Given the number: 17463 = 1 + 7 + 4 + 6 + 3 = 21
Sum of digits algorithmStep 1: Get number by user. Step 2: Get the modulus/remainder of the number. Step 3: sum the remainder of the number. Step 4: Divide the number by 10.
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 .
So, if the input is like num = 58612, then the output will be 22 because 5 + 8 + 6 + 1 + 2 = 22. while num is not equal to 0, do: sum := sum + num mod 10. num := num / 10.
You could do it arithmetically, without using a string:
sum = 0; while (n != 0) { sum += n % 10; n /= 10; }
I use
int result = 17463.ToString().Sum(c => c - '0');
It uses only 1 line of code.
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