首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >C#实现任意大数相加,不会溢出并且返回相加值。

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

作者头像
Echo_Wish
发布2023-11-30 18:44:19
发布2023-11-30 18:44:19
3460
举报

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);
        }
    }
}

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-11-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C#实现任意大数相加,不会溢出并且返回相加值。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档