67. Add Binary

来源:互联网 发布:微商软件总代理 编辑:程序博客网 时间:2024/06/06 08:58

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

For example,
a = "11"
b = "1"

Return "100".

public class Solution {    public String addBinary(String a, String b) {        int m = a.length();        int n = b.length();        String res = "";        int carry = 0;        int i = 0;        while(i<m || i<n || carry!=0){             int x = (i<m) ? a.charAt(m - 1 - i) - '0' : 0;             int y = (i<n) ? b.charAt(n - 1 - i) - '0' : 0;             res = (x + y + carry)%2 + res;             carry = (x + y + carry)/2;             i++;        }        return res;    }}