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?
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