Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of digits in C#

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

like image 419
Xn0vv3r Avatar asked Jan 26 '09 06:01

Xn0vv3r


People also ask

What is sum of digits in C?

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.

What is the formula for sum of digits?

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 .

How do you find the sum of 5 numbers in C?

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.


2 Answers

You could do it arithmetically, without using a string:

sum = 0; while (n != 0) {     sum += n % 10;     n /= 10; } 
like image 133
Greg Hewgill Avatar answered Sep 28 '22 16:09

Greg Hewgill


I use

int result = 17463.ToString().Sum(c => c - '0'); 

It uses only 1 line of code.

like image 39
Chaowlert Chaisrichalermpol Avatar answered Sep 28 '22 14:09

Chaowlert Chaisrichalermpol