张德长

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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

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

 

posted on   张德长  阅读(24)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示