class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
StringBuilder sba = new StringBuilder(a);
StringBuilder sbb = new StringBuilder(b);
int n =Math.max(a.length(),b.length());
int m =Math.min(a.length(),b.length());
if(a.length()>b.length()){
for (int i = 0; i < n-m; i++) {
sbb.insert(0,"0");
}
}else if(a.length()<b.length()) {
for (int i = 0; i < n-m; i++) {
sba.insert(0,"0");
}
}
int temp = 0;//进位标识符
int sum=0;
for (int i = n - 1; i >= 0; i--) {
sum = Character.getNumericValue(sba.charAt(i)) + Character.getNumericValue(sbb.charAt(i)) + temp;// 计算两个数字相加的值,加上之前的进位
temp = sum / 2;//是否进位
sum = sum % 2;
sb.append((char) (sum+'0'));
}
if (temp > 0) {
sb.append('1');
}
sb.reverse();
return sb.toString();
}
}
1、列竖式
- 相加大于等于2要进位;
- 两数长度不一样,缺位补0;
2、StringBuilder
当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类。
StringBuilder 相较于 StringBuffer 有速度优势
append(String s) | delete(int start, int end) |
reverse() | insert(int offset, int i) |