马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
借助BigInteger,虽然过了,效率贼差
import java.math.BigInteger;
class Solution {
public String addBinary(String a, String b) {
BigInteger bi1, bi2, bi3;
bi1 = new BigInteger(a,2);
bi2 = new BigInteger(b,2);
bi3 = bi1.add(bi2);
return bi3.toString(2);
}
}
然后选择分步来解决!
class Solution {
public String addBinary(String a, String b) {
StringBuilder A = new StringBuilder(a);
StringBuilder B = new StringBuilder(b);
A.reverse();
B.reverse();
while(A.length() > B.length()) B.append("0");
while(A.length() < B.length()) A.append("0");
int carry = 0, sum =0;
StringBuilder re = new StringBuilder("");
for(int i = 0; i< A.length(); i ++){
sum = carry + (A.charAt(i) - '0') + (B.charAt(i) - '0');
re.append(sum % 2);
carry = sum /2;
}
while(carry > 0){
re.append(carry % 2);
carry = carry /2;
}
re.reverse();
return re.toString();
}
}
|