Search code examples
c#listclasscomparetobigint

C# - Class that uses ILists to store huge integers without BigInt. Can't figure out how to use CompareTo and Int.TryParse to +, -, and * two Lists


I've been working on an assignment and I'm a beginner to C#. I have to implement a program that's similar to what BigInt can do: perform addition, subtraction, or multiplication with two absurdly large values (without actually using the BigInt library). I was told to use CompareTo and that it would make creating the add, subtract, and multiply methods easy, but I have no clue how to implement CompareTo. I don't even know if my class is implemented correctly or if I am missing something important. Here is my code:

public class HugeInt
{
    char sign;
    public IList<int> theInt = new List<int>();


    public string ToString(IList<int> theInt)
    {
        string bigInt = theInt.ToString();
        return bigInt;
    }

    public HugeInt CompareTo(HugeInt num1)
    {
        int numParse;
        string number = ToString(theInt); /// I did this to convert the List into a string
        for(int i = 0; i < number.Length; i++)
        {
            bool temp = Int32.TryParse(number, out numParse); /// Supposed to change each index of the string to a separate integer (not sure how to properly do this)

            /// These are *supposed to* perform operations on two HugeInts ///
            num1.plus(numParse, num1);
            num1.minus(numParse, num1);
            num1.times(numParse, num1);
        }

        return num1;
    }

I'm not here to ask for all the answers for this assignment, I've just been working on this for hours now and can't figure out what I'm doing wrong -- I have already done a lot of google searching. Thanks in advance for all advice and help!


Solution

  • To write such a class, it requires you know a little bit about how to do math by hand. For example, when adding two numbers, you start by adding their least significant digits. If the result is greater than 9, you have to carry a 1 to the next digit (explanation). Then you continue to the next digit.

    Now, here is my take on it. I want to save the "huge int" as a list of digits starting from the least significant digit. Then I implement the Plus method as described above. I can compare two "huge ints" by looking at the number of digits. The number with the most digits is the largest. In the case the number of digits are the same, I will need to compare each digit one-by-one, starting from the most significant digit.

    The below is just something to get you started. It only handles positive integers and has Plus and CompareTo methods. Be aware there are plenty of corner cases that I have not taken care of.

    It can be used like this:

    var num1 = new HugeInt("11112222333399998888777123123");
    var num2 = new HugeInt("00194257297549");
    
    Console.WriteLine(num1.Plus(num2).ToString()); // Writes 11112222333399999083034420672
    Console.WriteLine(num1.CompareTo(num2)); // Writes -1 since num1 > num2
    

    Here is the class:

    public class HugeInt
    {
        // The array that contains all the digits of the number. To create a new number, you do not change this array but instead you create a new instance of HugeInt.
        // The first digit is the least significant digit.
        private readonly int[] digits; 
    
        public HugeInt(string number)
        {
            // Trim off the leading zeros
            number = number.TrimStart('0');
            if (number == "")
                number = "0";
    
            // Convert to digit array with the least significant digit first
            digits = number.ToCharArray().Select(c => int.Parse(c.ToString())).Reverse().ToArray();
        }
    
        public HugeInt(IList<int> digits)
        {
            // Trim off the leading zeros
            var d = digits.ToList();
            while (d.Count > 1 && d.Last() == 0)
                d.RemoveAt(d.Count - 1);
    
            // Convert to digit array with the least significant digit first
            this.digits = d.ToArray();
        }
    
        public HugeInt Plus(HugeInt num)
        {
            // Add two positive integers by adding each digit together, starting with the least significant digit. 
            var result = new List<int>();
            int carry = 0;
            for (var i = 0; i < this.digits.Length || i < num.digits.Length; i++)
            {
                var digit1 = i < this.digits.Length ? this.digits[i] : 0;
                var digit2 = i < num.digits.Length ? num.digits[i] : 0;
                var digitResult = digit1 + digit2 + carry;
                carry = 0;
                if (digitResult >= 10)
                {
                    digitResult -= 10;
                    carry = 1;
                }
                result.Add(digitResult);
            }
            if (carry > 0)
                result.Add(carry);
    
            return new HugeInt(result);
        }
    
        public int CompareTo(HugeInt num)
        {
            // First compare by length of number
            if (this.digits.Length > num.digits.Length)
                return -1;
            else if (this.digits.Length < num.digits.Length)
                return 1;
            else
            {
                // If lengths are equal, then compare each digit - starting with the most significant digit.
                for (var i = this.digits.Length - 1; i >= 0; i--)
                {
                    var cmp = this.digits[i].CompareTo(num.digits[i]);
                    if (cmp != 0)
                        return cmp;
                }
                return 0;
            }
        }
    
        public override string ToString()
        {
            return String.Join("", digits.Reverse());
        }
    }