您的位置:首页 > 其它

二进制求和,lintcode

2016-12-11 14:04 423 查看
给定两个二进制字符串,返回他们的和(用二进制表示)。

样例

a = 11

b = 1

返回 100

解题思路:和十进制的求和没什么区别。注意细节就好了。下面的代码可以ac,但是冗余,可以优化为第二种方法。

一刷ac

public class Solution {
/**
* @param a a number
* @param b a number
* @return the result
*/
public String addBinary(String a, String b) {
if(a.length() == 0 && b.length() == 0) return "";
int carry = 0;
int i = a.length()-1;
int j = b.length()-1;
String res = "";
while(i >= 0 && j >= 0){
int value = carry + (a.charAt(i)-'0') + (b.charAt(j)-'0');
carry = value / 2;
value = value % 2;
res = String.valueOf(value) + res;
i--;
j--;
}
while(i >= 0){
int value = carry + a.charAt(i) - '0';
carry = value / 2;
value = value % 2;
res = String.valueOf(value) + res;
i--;
}
while(j >= 0){
int value = carry + b.charAt(j) - '0';
carry = value / 2;
value = value % 2;
res = String.valueOf(value) + res;
j--;
}
if(carry > 0)
res = String.valueOf(carry) + res;
return res;
}
}


public class Solution {
/**
* @param a a number
* @param b a number
* @return the result
*/
public String addBinary(String a, String b) {
if(a.length() == 0 && b.length() == 0) return "";
int i = a.length() - 1;
int j = b.length() - 1;
String res = "";
int carry = 0;
while(i >= 0 || j >= 0){
int sum = carry;
if(i >= 0) sum += a.charAt(i) - '0';
if(j >= 0) sum += b.charAt(j) - '0';
res = String.valueOf(sum % 2) + res;
carry = sum / 2;
i--;
j--;
}
if(carry > 0) res = String.valueOf(carry) + res;
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode