0

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

  • Please share what have you tried – Richa Garg Oct 27 '16 at 05:11
  • 1
    This is one of possible way to do it. Divide the number by 10 and accumulate the remainder and replace number with quotient in next iteration till the quotient is less then 10. – Adil Oct 27 '16 at 05:11
  • 2
    This question has already been answered before. http://stackoverflow.com/questions/478968/sum-of-digits-in-c-sharp – Bruce Smith Oct 27 '16 at 05:25

2 Answers2

1

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
oziomajnr
  • 1,671
  • 1
  • 15
  • 39
0

This isn't C# in particular, but you can loop over your number then get it digit by digit.

// -- c
int num = 134;
int sum = 0;
while(num != 0) {
    ones_digit = num % 10;
    sum += ones_digit;
    num = (num - ones_digit) / 10;
}

printf("sum: %d", sum);

On higher-level languages like javascript or python, accessing the digits can also be done by converting the integer to a string, then casting each char to an int type.

// -- javascript
var num = 134;
var digits = num.toString().split("").map(parseInt);
console.log(digits);
Jerome Indefenzo
  • 967
  • 6
  • 25