1、前言
题目描述2、思路
做法跟十进制加法差不多
3、代码
class Solution {
public String addBinary(String a, String b) {
int m = a.length(), n = b.length();
StringBuilder builder = new StringBuilder();
int te = 0;
int i = m - 1, j = n - 1;
for(; i >= 0 && j >= 0; i--, j--){
int aNum = a.charAt(i) - '0', bNum = b.charAt(j) - '0';
int sum = aNum + bNum + te;
int num = sum % 2;
te = sum / 2;
builder.insert(0, num);
}
while(i >= 0){
int sum = a.charAt(i--) - '0' + te;
te = sum / 2;
builder.insert(0, sum % 2);
}
while(j >= 0){
int sum = b.charAt(j--) - '0' + te;
te = sum / 2;
builder.insert(0, sum % 2);
}
while(te > 0){
builder.insert(0, te % 2);
te = te / 2;
}
return builder.toString();
}
}
网友评论