Search code examples
c#arrayschartype-conversionreturn

How to convert char array to int


How can I not find the solution for this one?

So I have a char array with numbers, and I want them joined together to a int.

I tried Convert.ToInt32, int.parse string.join and other tricks, yet I either don't know how to use them properly, or they are not fit for the job.

This is a assignment by returning a value to a test, what I get is a: System.FormatException: Input string was not in a correct format. That's how I know that something is wrong.

My code so far (focus on comment):

        public static int? NextBiggerThan(int number)
        {
            if (number < 0)
            {
                throw new ArgumentException(null);
            }
            else
            {
                char[] digit = number.ToString(CultureInfo.InvariantCulture.NumberFormat).ToCharArray();
                int n = digit.Length;
         // 
                for (int z = 0; z < n; z++)
                {
                    digit[z] -= '0';
                }

                int i;
                for (i = n - 1; i > 0; i--)
                {
                    if (digit[i] > digit[i - 1])
                    {
                        break;
                    }
                }

                if (i == 0)
                {
                    return null;
                }
                else
                {
                    int x = digit[i - 1], min = i;
                    for (int j = i + 1; j < n; j++)
                    {
                        if (digit[j] > x && digit[j] < digit[min])
                        {
                            min = j;
                        }
                    }

                    Swap(digit, i - 1, min);
                    Array.Sort(digit, i, n - i);
                    // number = ?????
                    return number;
                }
            }
        }

        public static void Swap(char[] digit, int i, int j)
        {
            char temp = digit[i];
            digit[i] = digit[j];
            digit[j] = temp;
        }

The rest of the code works fine, If I return for example digit[0], than it returns the value I want, however when I try connect everything at the end something goes wrong.


Solution

  • Join and int.Parse do work fine:

    namespace SandboxTests
    {
        public static class Extension
        {
            public static int ToInt(this char[] arr)
            {
                var str = string.Join("", arr);
                return int.Parse(str);
            }
        }
    
        [TestClass]
        public class JoinParseTests
        {
            [TestMethod]
            public void ExtensionToIntTest()
            {
                var sut = new[] { '3', '2', '1' };
                var intResult = sut.ToInt();
    
                Assert.AreEqual(321, intResult); // green
            }
        }
    }