public static GreatInt operator +(GreatInt GInt1, GreatInt GInt2) { //Cộng lần lượt các chữ số theo thứ tự phải qua trái. string s = ""; //lưu lại kết quả, theo chiều ngược; int extra = 0; //Số bù dư của phép cộng 2 chữ số //Việc cộng bắt đầu từ cuối 2 số đến đầu của Số dài nhất for (int i = GInt1.Length - 1, j = GInt2.Number.Length - 1; (j >= 0) || (i >= 0); i--, j--) { //Quy đồi chữ số kiểu char ra kiểu int để cộng int IntNum1 = (i < 0) ? IntNum1 = 48 : (int)GInt1.Number[i]; // nếu số thứ nhất ngắn hơn số thứ hai, sẽ cộng các chữ số của lại của số thứ hai với 0 ('0' đổi ra int 48) int IntNum2 = (j < 0) ? IntNum2 = 48 : (int)GInt2.Number[j]; int t = IntNum1 - 48 + IntNum2 - 48 + extra; //Khi tổng 2 số không đến 10 (không có số dư) thì extra=0; if (t < 10) { s += (char)(t + 48); extra = 0; } else //Còn khi cộng tổng 2 số hơn 10 (có số dư) thì extra =1; { s += (char)(t - 10 + 48); extra = 1; } } //thêm chữ số 1 nếu tràn. VD: 99+19 = 118 if(extra==1) { s += "1"; } //reverse Result String char[] sArr = s.ToCharArray(); Array.Reverse(sArr); string rs = new string(sArr); GreatInt result = new GreatInt(rs); return result; }
static void Main(string[] args) { bool exit = false; string command = ""; Console.Write("UITer's Software \"Add 2 Great Interger\" (version 1.0)\nProduced in 2012\n"); do { Console.Write("\nYour command: "); command = Console.ReadLine(); if (((command.Length == 5) && (command.Substring(0, 5)== CodeAdd2N.Key) || ((command.Length >= 6) && (command.Substring(0, 6) == (CodeAdd2N.Key+" "))))) { CodeAdd2N comAdd2N = new CodeAdd2N(command); if (!comAdd2N.Valid()) { Console.WriteLine(comAdd2N.ErrorMessage()); } else { GreatInt n1 = new GreatInt(comAdd2N.Number1()); GreatInt n2 = new GreatInt(comAdd2N.Number2()); Console.WriteLine("System Message: "+n1.Number+" + "+n2.Number+" = "+(n1 + n2).Number); } } else { if (command == "exit") { exit = true; }else Console.WriteLine("System Message: Command's not found"); } } while (exit == false); }