您的位置:首页 > 其它

lintcode-easy-Add Binary

2016-02-18 17:53 246 查看
Given two binary strings, return their sum (also a binary string).

Example

a =
11


b =
1


Return
100


这道题也没太多好说的……

public class Solution {
/**
* @param a a number
* @param b a number
* @return the result
*/
public String addBinary(String a, String b) {
// Write your code here

if(a == null)
return b;
if(b == null)
return a;

if(a.length() == 0)
return b;
if(b.length() == 0)
return a;

int p1 = a.length() - 1;
int p2 = b.length() - 1;

StringBuilder result = new StringBuilder();

int carry = 0;

while(p1 >= 0 || p2 >= 0){
int bit_a = 0;
int bit_b = 0;

if(p1 >= 0){
bit_a = (int) (a.charAt(p1) - '0');
p1--;
}
if(p2 >= 0){
bit_b = (int) (b.charAt(p2) - '0');
p2--;
}

result.insert(0, (bit_a + bit_b + carry) % 2);
carry = (bit_a + bit_b + carry) / 2;

}

if(carry == 1)
result.insert(0, 1);

return result.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: