zoukankan      html  css  js  c++  java
  • 大数运算(任意两大数相加)

    我们的计算器一般计算范围最多都要十几位到二十几位,如果要计算一个很大的数那么用计算器就不管用了吧,为了能计算两个大数相加,就根据加法的原理来写一个算法吧。

    原理:两数相加,从个位开始相加,满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 }
  • 相关阅读:
    013.ES6 -对象字面量增强型写法
    012. ES6
    011. ES6 语法
    10. 9. Vue 计算属性的setter和getter 以及 计算属性的缓存讲解
    4. Spring MVC 数据响应方式
    3. SpringMVC 组件解析
    9. Vue 计算属性
    【洛谷 2984】给巧克力
    【洛谷 1821】捉迷藏 Hide and Seek
    【洛谷 1821】银牛派对Silver Cow Party
  • 原文地址:https://www.cnblogs.com/xiaoyu5062/p/2568735.html
Copyright © 2011-2022 走看看