牛客[编程题] 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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix