# [leetcode]Add Binary

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

For example,
a = “11”
b = “1”
Return “100”.

public String addBinary(String a, String b) {
int res = BinaryToInt(a) + BinaryToInt(b);
return Integer.toBinaryString(res);
}
public int BinaryToInt(String num){
int res = 0;
for(int i = 0; i < num.length(); i++){
res += (Math.pow(2, i)) * (num.charAt(num.length() - i - 1) - '0');
}
return res;
}

public class Solution {
public String addBinary(String a, String b) {
a = reverseStr(a);
b = reverseStr(b);
String longerStr = a.length() > b.length() ? a : b;
String shortterStr = a.length() > b.length() ? b : a;
String res = "";
int i, tmp, carry = 0;
for(i = 0; i < shortterStr.length(); i++){
tmp = shortterStr.charAt(i) - '0' + longerStr.charAt(i) - '0' + carry;
if(tmp >= 2){
tmp -= 2;
carry = 1;
}else{
carry = 0;
}
res += String.valueOf((char)(tmp + '0'));
}
for(; i < longerStr.length(); i++){
tmp = longerStr.charAt(i) - '0' + carry;
if(tmp >= 2){
tmp -= 2;
carry = 1;
}else{
carry = 0;
}
res += String.valueOf((char)(tmp + '0'));
}
if(carry == 1) res += "1";
return reverseStr(res);
}
public String reverseStr(String s){
StringBuffer sb=new StringBuffer(s);
sb.reverse();
return sb.toString();
}
}

1. java中反转字符串的方法（利用StringBuffer）；
2. String.valueOf((char)(tmp + ‘0’))这里，要进行强制转换。

#### Add Binary | leetcode 67 【Java解题报告】

2015-10-04 14:23:39

#### leetcode 67 Add Binary

2015-07-05 21:49:19

#### LeetCode 67 : Add Binary (Java)

2015-12-03 21:08:20

#### [leetcode](Add Binary C语言实现)

2015-04-21 12:55:39

#### 67. Add Binary [easy] (Python)

2016-06-18 17:29:55

#### [leetcode-67]Add Binary(C)

2015-08-02 22:41:45

#### 67. Add Binary Leetcode Python

2015-02-04 23:43:05

#### Add Binary -- LeetCode

2014-03-01 06:30:43

#### leetcode解题之67 # Add Binary Java版

2017-03-13 10:40:25

#### 【LeetCode-面试算法经典-Java实现】【067-Add Binary（二进制加法）】

2015-08-02 06:09:41