编程语言
首页 > 编程语言> > 常考面试题之两个字符串相加(长整数相加)C#版

常考面试题之两个字符串相加(长整数相加)C#版

作者:互联网

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace wsy
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = Console.ReadLine();
            int aLength = a.Length;

            string b = Console.ReadLine();
            int bLength = b.Length;

            List<string> aList = new List<string>();

            for (int i = aLength - 1; i >= 0; i--)
            {
                aList.Add(a[i].ToString());
            }

            List<string> bList = new List<string>();

            for (int i = bLength - 1; i >= 0; i--)
            {
                bList.Add(b[i].ToString());
            }


            List<int> result = new List<int>();

            int maxLength = aLength > bLength ? aLength : bLength;

            if (aLength > bLength)
            {
                for (int i = 0; i < aLength - bLength; i++)
                {
                    bList.Add("0");
                }
            }
            else
            {
                for (int i = 0; i < bLength - aLength; i++)
                {
                    aList.Add("0");
                }
            }

            string[] aString = aList.ToArray();
            string[] bString = bList.ToArray();

            int next = 0;

            for (int i = 0; i < maxLength; i++)
            {
                int num = int.Parse(aString[i]) + int.Parse(bString[i]) + next;
                next = 0;
                if (i != maxLength - 1)
                {
                    if (num >= 10)
                    {
                        next = 1;
                        result.Add(num - 10);
                    }
                    else
                    {
                        result.Add(num);

                    }

                }

                else
                {
                    if (num > 10)
                    {
                        result.Add(num - 10);
                        result.Add(1);
                    }
                    else
                    {
                        result.Add(num);
                    }
                }
            }

            int[] re = result.ToArray();

            for (int i = re.Length-1; i >= 0; i--)
            {
                Console.Write(re[i]);
            }

            Console.ReadKey();
        }
    }
}

最笨的方式。。。。

标签:bLength,面试题,int,常考,相加,Add,num,result,aLength
来源: https://blog.csdn.net/qq_40299598/article/details/112885724