0

My end goal is to take a number like 29, pull it apart and then add the two integers that result. So, if the number is 29, for example, the answer would be 2 + 9 = 11.

When I'm debugging, I can see that those values are being held, but it appears that other values are also being incorrect in this case 50, 57. So, my answer is 107. I have no idea where these values are coming from and I don't know where to begin to fix it.

My code is:

class Program
{
    static void Main(string[] args)
    {
        int a = 29;
        int answer = addTwoDigits(a);
        Console.ReadLine();


    }
        public static int addTwoDigits(int n)
        {
            string number = n.ToString();
            char[] a = number.ToCharArray();
            int total = 0;

            for (int i = 0; i < a.Length; i++)
            {
                total = total + a[i];
            }
            return total;
        }

}
s.m.
  • 7,895
  • 2
  • 38
  • 46

8 Answers8

3

As mentioned the issue with your code is that characters have a ASCII code value when you cast to int which doesn't match with the various numerical digits. Instead of messing with strings and characters just use good old math instead.

public static int AddDigits(int n)
{
    int total = 0;
    while(n>0)
    {
        total += n % 10;
        n /= 10;
    }

    return total;
}

Modulo by 10 will result in the least significant digit and because integer division truncates n /= 10 will truncate the least significant digit and eventually become 0 when you run out of digits.

juharr
  • 31,741
  • 4
  • 58
  • 93
1

Your code is actually additioning the decimal value of the char.
Take a look at https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

Decimal value of 2 and 9 are 50 and 57 respectively. You need to convert the char into a int before doing your addition.

int val = (int)Char.GetNumericValue(a[i]);
0

Your problem is that you're adding char values. Remember that the char is an integer value that represents a character in ASCII. When you are adding a[i] to total value, you're adding the int value that represents that char, the compiler automatic cast it.

The problem is in this code line:

total = total + a[i];

The code above is equal to this code line:

total += (int)a[i];

// If a[i] = '2', the character value of the ASCII table is 50.
// Then, (int)a[i] = 50.

To solve your problem, you must change that line by this:

total = (int)Char.GetNumericValue(a[i]);

// If a[i] = '2'.
// Then, (int)Char.GetNumericValue(int)a[i] = 2.

You can see this answer to see how to convert a numeric value from char to int.

At this page you can see the ASCII table of values.

CryogenicNeo
  • 937
  • 12
  • 25
0

Just for fun, I thought I'd see if I could do it in one line using LINQ and here it is:

public static int AddWithLinq(int n)
{
    return n.ToString().Aggregate(0, (total, c) => total + int.Parse(c.ToString()));
}

I don't think it would be particularly "clean" code, but it may be educational at best!

Matt Hogan-Jones
  • 2,981
  • 1
  • 29
  • 35
0

Try this:

public static int addTwoDigits(int n)
    {
        string number = n.ToString();
        char[] a = number.ToCharArray();
        int total = 0;

        for (int i = 0; i < a.Length; i++)
        {
            total = total + (int)Char.GetNumericValue(a[i]);
        }
        return total;
    }

Converted number to char always returns ASCII code.. So you can use GetNumericValue() method for getting value instead of ASCII code

Ajay Reddy
  • 113
  • 6
0

You should you int.TryParse

  int num; 
 if (int.TryParse(a[i].ToString(), out num))
  {
      total += num; 
   }
0
public static int addTwoDigits(int n)
{
    string number = n.ToString()
    char[] a = number.ToCharArray();

    int total = 0;

    for (int i = 0; i < a.Length; i++)
    {
        total +=  Convert.ToInt32(number[i].ToString());
    }
    return total;
}
Benjamin RD
  • 11,516
  • 14
  • 87
  • 157
  • @FHTMitchell sure, if you use `number[i].ToString()` you're getting the value as char, and contacting a a number to his value. Then, you have to convert it the `char` to number, but, in c# is not . possible do it directly, then, you have to convert it to `string` first and later as `Int3`. Now, you can operate 2 integer values. – Benjamin RD May 11 '18 at 17:04
0

You don't need to convert the number to a string to find the digits. @juharr already explained how you can calculate the digits and the total in a loop. The following is a recursive version :

int addDigit(int total,int n)
{
    return (n<10) ? total + n
                  : addDigit(total += n % 10,n /= 10);
}

Which can be called with addDigit(0,234233433)and returns 27. If n is less than 10, we are counting the last digit. Otherwise extract the digit and add it to the total then divide by 10 and repeat.

One could get clever and use currying to get rid of the initial total :

int addDigits(int i)=>addDigit(0,i);

addDigits(234233433) also returns 27;

If the number is already a string, one could take advantage of the fact that a string can be treated as a Char array, and chars can be converted to ints implicitly :

var total = "234233433".Sum(c=>c-'0');

This can handle arbitrarily large strings, as long as the total doesn't exceed int.MaxValue, eg:

"99999999999999999999".Sum(x=>x-'0');  // 20 9s returns 180

Unless the number is already in string form though, this isn't efficient nor does it verify that the contents are an actual number.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236