36进制加法
约 352 字大约 1 分钟
2025-03-02
36进制由0-9,a-z,共36个字符表示。
要求按照加法规则计算出任意两个36进制正整数的和,如1b + 2x = 48 (解释:47+105=152)
要求:不允许使用先将36进制数字整体转为10进制,相加后再转回为36进制的做法
36进制字符与数值的转换,类似十进制的大数相加,注意将10
变成36
。
class Solution {
// 将整数转换为对应的36进制字符
public static char getChar(int n) {
if (n <= 9)
return (char)(n + '0');
else
// 10代表a
return (char)(n - 10 + 'a');
}
// 将36进制字符转换为对应的整数。36进制数是0-9,a-z。
public static int getInt(char ch) {
if ('0' <= ch && ch <= '9')
return ch - '0';
else
// a 代表10
return ch - 'a' + 10;
}
// 添加两个36进制字符串
public static String add36Strings(String num1, String num2) {
int carry = 0;
int i = num1.length() - 1, j = num2.length() - 1;
int x, y;
StringBuilder res = new StringBuilder();
// 遍历两个字符串,同时处理进位
while (i >= 0 || j >= 0 || carry != 0) {
// 计算前要先把字符转换为整数
x = i >= 0 ? getInt(num1.charAt(i)) : 0;
y = j >= 0 ? getInt(num2.charAt(j)) : 0;
int temp = x + y + carry;
res.append(getChar(temp % 36)); // 将当前位的结果加入StringBuilder
carry = temp / 36; // 更新进位,进位不需要被转为字符。
i--;
j--;
}
return res.reverse().toString(); // 反转结果字符串并返回
}
}