题目

思路
- 字符串相加
- 用
toInt()和toChar()辅助
代码
public class Add {
public String add(String s1, String s2) {
StringBuffer sb = new StringBuffer();
int i = s1.length() - 1, j = s2.length() - 1;
int carry = 0;
while (i >= 0 || j >= 0 || carry != 0) {
int num1 = i >= 0 ? toInt(s1.charAt(i)) : 0;
int num2 = j >= 0 ? toInt(s2.charAt(j)) : 0;
int sum = num1 + num2 + carry;
carry = sum / 36;
int cur = sum % 36;
sb.append(toChar(cur));
i--;
j--;
}
return sb.reverse().toString();
}
public int toInt(char c) {
if ('0' <= c && c <= '9') {
return c - '0';
} else {
return 10 + c - 'a';
}
}
public char toChar(int n) {
if (0 <= n && n <= 9) {
return (char) (n + '0');
} else {
return (char) (n - 10 + 'a');
}
}
public static void main(String[] args) {
Add a = new Add();
System.out.println(a.add("1b", "2x"));
}
}