Closed PisecesPeng closed 3 years ago
public static String func(String a, String b) {
int rTmp = Integer.valueOf(a).intValue() + Integer.valueOf(b).intValue();
String result = "";
boolean plusOne = false; // '是否进位'状态
while (rTmp > 0) {
int r = rTmp % 10; // 取得个位数
// 判断当前个位数, 且判断'是否进位', 向前累加值, 并更新'是否进位'状态
if (r == 0) {
if (plusOne) result = "1" + result;
else result = "0" + result;
plusOne = false;
} else if (r == 1) {
if (plusOne) result = "0" + result;
else result = "1" + result;
} else {
if (plusOne) result = "1" + result;
else result = "0" + result;
plusOne = true;
}
rTmp /= 10;
}
// 确认首位是否还需要进位
if (plusOne) result = "1" + result;
return result;
}
public static String func(String a, String b) {
return Integer.toBinaryString(
Integer.parseInt(a, 2) + Integer.parseInt(b, 2)
);
}
public static String func(String a, String b) {
StringBuffer ans = new StringBuffer();
int n = Math.max(a.length(), b.length()), carry = 0;
for (int i = 0; i < n; ++i) {
carry += i < a.length() ? (a.charAt(a.length() - 1 - i) - '0') : 0;
carry += i < b.length() ? (b.charAt(b.length() - 1 - i) - '0') : 0;
ans.append((char) (carry % 2 + '0'));
carry /= 2;
}
if (carry > 0) {
ans.append('1');
}
ans.reverse();
return ans.toString();
}
二进制求和
给定两个二进制字符串, 返回他们的和(用二进制表示).
输入为非空字符串且只包含数字
1
和0
.题目地址: https://leetcode-cn.com/problems/add-binary/