Question

I am trying to write a code that sums the digits of a number and it should work, but I can't find where I am doing it wrong, I have a working code in Python for this and I tried to do it the same way in C# but.. Here are the two codes

Python:

number = "12346546"
summ=0
for i in number:
    summ+=int(i)
print summ

C#:

string num = "2342";
int sum = 0;

for (int i = 0; i < num.Length; i++)
{
    int number = Convert.ToInt32(num[i]);
    sum += number;
}
Console.WriteLine(sum);

Edit: I used the Debugger and I found that when I am converting the numbers they turn out to be completely different numbers, but if I convert the whole string then it is converting correctly... how to fix this?

Was it helpful?

Solution

num[i] is a char and Convert.ToInt32 will return the ASCII code of the char instead of the actual numerical value.Use:

int number = Convert.ToInt32(num[i].ToString());

Also change i < num.Length-1 to i < num.Length

Edit: To make it more clear here is an example:

int n1 = Convert.ToInt32('0'); // Uses Convert.ToInt32(char) result -> 48
int n2 = (int) '0'; // cast from char to int result -> 48
int n3 = Convert.ToInt32("0"); // Uses Convert.ToInt32(string) result -> 0

OTHER TIPS

replace Convert.ToInt32(num[i])

by

Convert.ToInt32(num[i].ToString())

else, you will get an ascii value... (cause num[i] is a char)

see msdn

There is no null at the end of a C# string, so you don't have to worry about it, and thus do not require the "-1" in your loop. However, there is a much easier way:

string num = "2342";
int sum = num.ToCharArray().Select(i => int.Parse(i.ToString())).Sum();

This converts the string to a character array, converts them all to ints (returning an IEnumerable<int> in the process) and then returns the sum of them all.

Convert.ToInt32(num[i]); would give you the ASCII value for the character digit. For example for character 1 you will get 49.

Use char.GetNumericValue like:

for (int i = 0; i < num.Length; i++)
{
    int number = (int) char.GetNumericValue((num[i]));
    sum += number;
}

You also need to modify your loop to continue till Length, since you are using <.

If you want to use LINQ then you can do:

int sum = num.Select(r => (int)char.GetNumericValue(r)).Sum();

A one line solution using Linq:

string num = "2342";
int sum = num.Sum(c=> Convert.ToInt32(c.ToString()));

Here's a fiddle: https://dotnetfiddle.net/3jt7G6

You can combine a few things.

You can select a collection of chars from a string using Linq (Sum() is a Linq method).

You still need to convert those characters into numbers; you can do this by converting a character to a string and parsing that or you can use another built-in method.

var sum = num.Sum(i => Char.GetNumericValue(i));

char is, at its core, just a number. It just happens to be a number representing a character.

Here are some solutions that highlight this:

int sum = num.Sum(c => c) - '0' * num.Length;

// or

int sum = 0;    
for (int i = 0; i < num.Length; i++)
{
    sum += num[i] - '0';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top