Question

numbers[i] = numbers[i] * 2;

if (numbers[i] >= 10)
{
   string t = numbers[i].ToString();
   Console.WriteLine(t[0] + " plus " + t[1]+" = "+quersumme(t).ToString());
   numbers[i] = Convert.ToInt32(t[0]) + Convert.ToInt32(t[1]);
}

public int quersumme(string n)
{
   return n[0] + n[1];
}

The function returns 101 when I enter 7. But 7 * 2 = 14 and quersumme should do 1+4 = 5

Was it helpful?

Solution

t[0] is the character '1', and t[1] is the character '4', which is translated to 49 + 52, hence 101. Check out an ASCII chart to see what I'm talking about.

You could try using the Char.GetNumericValue() function:

return (int)Char.GetNumericValue(n[0]) + (int)Char.GetNumericValue(n[1]);

OTHER TIPS

You're currently summing the Unicode code points - '1' is 49, and '4' is 52, hence the 101. You want to take the digit value of each character.

If you know that the digits will be in the range '0'-'9', the simplest way of doing that is just to subtract '0' and to use the LINQ Sum method to sum each value:

public int SumDigits(string n)
{
   return n.Sum(c => c - '0');
}

Or you could use Char.GetNumericValue(), but that returns double because it also copes with characters such as U+00BD: ½.

Try converting n[0] and n[1] to separate int32's in your quersomme function

You are doing string concatenation in quesumme method.

Should be:

public int quersumme(string n)
{
   return (int)Char.GetNumericValue(n[0]) + (int)Char.GetNumericValue(n[1]);
}

It looks to me like you are trying to enumerate the digits in an int.

Try this to avoid slow and cumbersome parsing and conversion. (Its all relative, I haven't tested performance.)

static IEnumerable<int> EnumerateDigits(int value, int baseValue = 10)
{
    while (value > 0)
    {
        yield return value % baseValue;
        value = value / baseValue
    }
}

Then, if you want to switch the order into an array

var t = EnumerateDigits(numbers[i]).Reverse().ToArray();

But, if you just want to sum the digits.

var checksum = EnumerateDigits(numbers[i]).Sum()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top