LeetCode刷题笔录Add Binary

Given two binary strings, return their sum (also a binary string).

For example,

a = "11"

b = "1"

Return "100".

详细一位一位地加即可了,考虑进位的问题。还有最后记得把生成的string反过来再返回,由于我们是从最低位開始加的。

public class Solution {
public String addBinary(String a, String b) {
if(a == null || a.length() == 0)
return b;
if(b == null || b.length() == 0)
return a; StringBuilder res = new StringBuilder(); int i = a.length() - 1;
int j = b.length() - 1;
int digit;
int carry = 0; while(i >= 0 && j >= 0){
digit = (int)(a.charAt(i) - '0' + b.charAt(j) - '0' + carry);
carry = digit / 2;
digit %= 2; res.append(digit);
i--;
j--;
} while(i >= 0){
digit = (int)(a.charAt(i) - '0' + carry);
carry = digit / 2;
digit %= 2; res.append(digit);
i--;
} while(j >= 0){
digit = (int)(b.charAt(j) - '0' + carry);
carry = digit / 2;
digit %= 2; res.append(digit);
j--;
}
//don't forget to add the final carry(if exists)
if(carry > 0){
res.append(carry);
} return res.reverse().toString();
}
}
上一篇:【LeetCode】108. Convert Sorted Array to Binary Search Tree


下一篇:【leetcode❤python】 67. Add Binary