C#实现任意大数相加,不会溢出并且返回相加值。

2023-11-30 18:44:19 浏览数 (1)

C#实现任意大数相加,不会溢出并且返回相加值。

代码语言:javascript复制
using System;
using System.Collections;
using System.Runtime.InteropServices.ComTypes;
using System.Text;

namespace day15test02
{
    class Program
    {
        /// <summary>
        /// 任何大数相加不溢出
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            getAdd("13854864869486418641", "416848648694684684867431443494");
        }
        
        //当输入的的相加大于long的范围是,该方法进行逐位相加
        public static void getAdd(String s1, String s2)
        {
            int max = 0, min = 0;
            char[] chi = s1.ToCharArray();
            char[] chl = s2.ToCharArray();
            if (chi.Length >= chl.Length) { max = chi.Length; min = chl.Length; }
            if (chi.Length < chl.Length) { max = chl.Length; min = chi.Length; }
            int[] il = new int[max   1];
            int by;
            int i = max - 1;
            for (int j = min - 1; j >= 0; j--)
            {
                if(max == chi.Length) 
                { by = (byte)(chi[i] - '0')   (byte)(chl[j] - '0'); }
                else { by = (byte)(chl[i] - '0')   (byte)(chi[j] - '0'); }
                if (by >= 10) { il[i   1] = by - 10; il[i]  ; }
                if (by < 10) { il[i   1] = by; }
                i--;
            }
            StringBuilder ss = new StringBuilder();
            for (int x = 1; x < il.Length; x  ) { ss.Append(il[x]); }
            ss.Replace("0","");
            Console.WriteLine(ss);
        }
    }
}

一个小练习,供大家参考。

0 人点赞