大数运算(任意两大数相加)
我们的计算器一般计算范围最多都要十几位到二十几位,如果要计算一个很大的数那么用计算器就不管用了吧,为了能计算两个大数相加,就根据加法的原理来写一个算法吧。
原理:两数相加,从个位开始相加,满10进1。
实现:
创建控制台应用程序,代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 5 namespace BigNum { 6 class Program { 7 static string a, b, c, lastStr; static int tempX; static int[ ] x; static int[ ] y; 8 static void Main ( string[ ] args ) { 9 c = ( a = "0" + Console.ReadLine ( ) ) + ( b = "0" + Console.ReadLine ( ) ); 10 c = ( a.Length >= b.Length ) ? ( b = ( b.PadLeft ( a.Length ).Replace ( " ", "0" ) ) ) : ( a = ( a.PadLeft ( b.Length ).Replace ( " ", "0" ) ) ); 11 int[ ] temp = new int[a.Length]; 12 x = Array.ConvertAll ( a.ToCharArray ( ), new Converter<char, int> ( ToType ) ); 13 y = Array.ConvertAll ( b.ToCharArray ( ), new Converter<char, int> ( ToType ) ); 14 for ( int i = b.Length - 1; i > -1; i-- ) { 15 tempX = ( ( x[i] + y[i] ) >= 10 ) ? ( ( x[i - 1]++ ) & ( temp[i] = x[i] + y[i] - 10 ) ) : ( temp[i] = x[i] + y[i] ); } 16 foreach ( int s in temp ) { lastStr += s.ToString ( ); } 17 while ( lastStr[0].ToString ( ) == "0"&& lastStr .Length >1 ) { lastStr = lastStr.Remove ( 0, 1 ); } 18 Console.WriteLine ( lastStr ); Console.ReadKey ( );} 19 public static int ToType ( char xx ) { return int.Parse ( xx.ToString ( ) );} 20 } 21 }