详细见:leetcode.com/problems/add-binary
Java Solution: github
package leetcode;
/*
* Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
*/
public class P067_AddBinary {
public static void main(String[] args) {
System.out.println(new Solution().addBinary("11111", "1"));
}
/*
* 一次AC,好爽!!!
* 3 ms
* 89.82%
*/
static class Solution {
public String addBinary(String a, String b) {
int m = 0, n = 0;
if (a == null || b == null || (m = a.length()) == 0 || (n = b.length()) == 0)
return m == 0 ? b : a;
if (m > n)
return addBinary(b, a);
int[] sum = new int[n];
int carry = 0;
while (true) {
m --;
n --;
if (m > -1)
sum[n] = a.charAt(m) - '0';
if (n == -1)
break;
sum[n] += carry;
sum[n] += b.charAt(n) - '0';
carry = sum[n] / 2;
sum[n] = sum[n] % 2;
}
char[] cs = new char[carry + b.length()];
cs[0] = '1';
for (int i = carry; i != cs.length; i ++)
cs[i] = sum[i - carry] == 0 ? '0' : '1';
return new String(cs);
}
}
}
C Solution: github
/*
url: leetcode.com/problems/add-binary
*/
#include <stdio.h>
#include <stdlib.h>
char* addBinary(char* a, char* b) {
int ai = 0, bi = 0, c = 0, ansi = 0;
char * ans = NULL;
while (a[ai] != '\0') ai ++;
while (b[bi] != '\0') bi ++;
ans = (char*) malloc(sizeof(ai + bi + 1));
ai --;
bi --;
ans[ai + bi] = '\0';
ansi = ai + bi - 1;
while (ai > -1 && bi > -1) {
c = a[ai] - '0' + b[bi] - '0' + c;
ans[ansi] = (char)('0' + (c % 2));
c = c / 2;
ai --;
bi --;
ansi --;
}
while (ai > -1) {
c = a[ai] - '0' + c;
ans[ansi] = (char)('0' + (c % 2));
c = c / 2;
ai --;
ansi --;
}
while (bi > -1) {
c = b[bi] - '0' + c;
ans[ansi] = (char)('0' + (c % 2));
c = c / 2;
bi --;
ansi --;
}
if (c != 0) {
ans[ansi] = (char)('0' + (c % 2));
ansi --;
}
return ans + ansi + 1;
}
int main() {
char* a = "11";
char* b = "1";
char* ans = addBinary(a, b);
printf("answer is: \r\n%s\r\n", ans);
//free(ans);
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/add-binary/
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月15日
@details: Solution: 68ms 40.59%
'''
from jinja2._compat import unichr
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
an = 0 if a == None else len(a)
bn = 0 if b == None else len(b)
if an == 0 or bn == 0:
return a if bn == 0 else b
c, ai , bi, ans = 0, an-1, bn - 1, []
while ai > -1 and bi > -1:
c += (int(a[ai]) + int(b[bi]))
ans.append(unichr(ord('0')+(c%2)))
c = c // 2
ai, bi = ai-1, bi-1
while ai > -1:
c += (int(a[ai]))
ans.append(unichr(ord('0')+(c%2)))
c = c // 2
ai -= 1
while bi > -1:
c += (int(b[bi]))
ans.append(unichr(ord('0')+(c%2)))
c = c // 2
bi -= 1
if c != 0:
ans.append(unichr(ord('0')+(c%2)))
while len(ans) != 1 and ans[len(ans)-1] == '0': ans.pop()
ans.reverse()
return "".join(ans)
if __name__ == "__main__":
print(Solution().addBinary("0", "0"))