牛客[编程题] HJ57 高精度整数加法

发布时间 2023-11-09 17:07:26作者: 张德长
HJ57 高精度整数加法
中等  通过率:36.15%  时间限制:1秒  空间限制:32M
 

描述

输入两个用字符串 str 表示的整数,求它们所表示的数之和。
 
数据范围: 1 \le len(str) \le 10000 \

输入描述:

输入两个字符串。保证字符串只含有'0'~'9'字符

输出描述:

输出求和后的结果

示例1

输入:
9876543210
1234567890
输出:
11111111100

 

 using System;
    using System.Collections.Generic;
    class Program
    {
        public static void Main()
        {
            string line;
            string line1 = null;
            string line2 = null;
            while ((line = System.Console.ReadLine()) != null)
            { // 注意 while 处理多个 case
                if (line1 == null)
                {
                    line1 = line;
                }
                else
                {
                    line2 = line;
                    int maxLen = line1.Length > line2.Length ? line1.Length : line2.Length;
                    int carry = 0;
                    string res = string.Empty;
                    int pos1, pos2;
                    int temp;
                    var dic = GetDic();
                    for (int i = 0; i < maxLen+1; i++)
                    {
                        pos1 = line1.Length - 1 - i;
                        pos2 = line2.Length - 1 - i;
                        if (pos1 >= 0 && pos2 >= 0)
                        {
                            temp = dic[line1[pos1]] + dic[line2[pos2]] + carry;
                            res = res.Insert(0, (temp % 10).ToString());
                            carry = temp / 10;
                        }
                        else if (pos1>=0&& pos2<0)
                        {
                            temp= dic[line1[pos1]] + carry;
                            res = res.Insert(0, (temp % 10).ToString());
                            carry = temp / 10;
                        }
                        else if (pos1 < 0 && pos2 >= 0)
                        {
                            temp = dic[line2[pos2]] + carry;
                            res = res.Insert(0, (temp % 10).ToString());
                            carry = temp / 10;
                        }
                        else if (pos1 < 0 && pos2 <0&&carry>0)
                        {
                            res = res.Insert(0, carry.ToString());
                        }
                    }
                    Console.WriteLine(res);




                    return;
                }

            }
        }
        static Dictionary<char, int> GetDic()
        {
            Dictionary<char, int> dic = new Dictionary<char, int>();
            dic.Add('0', 0);
            dic.Add('1', 1);
            dic.Add('2', 2);
            dic.Add('3', 3);
            dic.Add('4', 4);
            dic.Add('5', 5);
            dic.Add('6', 6);
            dic.Add('7', 7);
            dic.Add('8', 8);
            dic.Add('9', 9);
            return dic;
        }
    }