-4

How to sum different digits in one integer? For example: int = and 411; I want to pull out the numbers and sum them: 4 + 1 + 1 = 6, tried in various ways, but I gather ASCII value in the table, and I do not want it?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Nick1R1
  • 1
  • 2
  • 2
    Dont be worry to show your failed attempts, nobody will make fun of you for your code. Instead just asking someone to solve your problem is not well accepted here. Read the [help] – Steve Aug 15 '15 at 16:51

2 Answers2

1

How about using a LINQ expression?

var sum = 411.ToString().Sum(x => x - '0');

By turning the int value into a string (which implements IEnumerable<char>), we're able to iterate over each digit and sum them.

rsenna
  • 11,775
  • 1
  • 54
  • 60
Eser
  • 12,346
  • 1
  • 22
  • 32
0
int i = 441;
int sum = 0;
while (i > 0)
{
    sum += i%10;
    i /= 10;
}
Backs
  • 24,430
  • 5
  • 58
  • 85