二十进制数的加法
题目详情
在二十进制中,我们除了使用数字0-9以外,还使用字母a-j(表示10-19),给定两个二十进制整数,求它们的和。
输入是两个二十进制整数,且都大于0,不超过100位;
输出是它们的和(二十进制),且不包含首0。我们用字符串来表示二十进制整数。
class Program { static void Main(string[] args) { string s = Sum("abc", "abc"); // 1134 Console.WriteLine(s); Console.Read(); } /// <summary> /// 二十进制相加 /// </summary> /// <param name="a">字符串a</param> /// <param name="b">字符串b.</param> /// <returns></returns> static string Sum(string a, string b) { int len = a.Length > b.Length ? a.Length + 1 : b.Length + 1; char[] ar = new char[len]; int i = 0; int ai = a.Length - 1; int bi = b.Length - 1; int t; int ad = 0; while (ai >= 0 || bi >= 0) { if (ai >= 0 && bi >= 0) { t = Map(a[ai]) + Map(b[bi]) + ad; } else if (ai >= 0) { t = Map(a[ai]) + ad; } else { t = Map(b[bi]) + ad; } ar[i++] = RMap(t % 20); ad = t / 20; ai--; bi--; } if (ad > 0) { ar[i] = '1'; } int h = ar.Length - 1; while (ar[h] == '\0') { h--; } string s = ""; while (h >= 0) { s += ar[h--]; } return s; } /// <summary> /// Maps the specified c. /// a -> 10 , j-> 19 , others exception /// </summary> /// <param name="c">The c.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">c</exception> static int Map(char c) { c = char.ToLower(c); if (c >= 'a' && c <= 'j') { return 10 + (c - 'a'); } throw new ArgumentException("c"); } /// <summary> ///Map int to char, 10 -> a , 19 -> j /// </summary> /// <param name="i">The i.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">i</exception> static char RMap(int i) { if (i >= 10 && i <= 19) { return Convert.ToChar(87 + i); } else if (i < 10) { return i.ToString()[0]; } throw new ArgumentException("i"); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述