rayho - 1 month ago 8

C# Question

can you help me figure out how to calculate this way, for example I have some integer:

first I need condition

if (x < 10) to avoid asked calculation for single numbers

now if number contains more then 1 digit need to calculate it second way, for example, I got 134 how to separate it to calculate it this way 1 + 3 + 4 to attach this value 8 to variable.

So question is how to separate numbers

Answer

try

```
int num = 12345;
// holder temporarily holds the last digit of the number
int holder = 0;
int sum = 0;
while (num>0)
{
holder = num%10;
num = num/10;
sum += holder;
}
//sum would now hold the sum of each digit
```

Source (Stackoverflow)

Comments