Add Binary

来源:互联网 发布:js怎么调用java的方法 编辑:程序博客网 时间:2024/06/09 22:16

Q:

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

For example,
a = "11"
b = "1"
Return "100".

Solution:

public class Solution {    public String addBinary(String a, String b) {        String result = "";        int i = a.length() - 1;        int j = b.length() - 1;        int carry = 0;        while (i >= 0 || j >= 0) {            int ai = i >= 0? a.charAt(i) - '0': 0;            int bj = j >= 0? b.charAt(j) - '0': 0;            int bit = (ai + bj + carry) % 2;            carry = (ai + bj + carry) / 2;            result = bit + result;            i--;            j--;        }        if (carry == 1)            result = carry + result;        return result;    }}


0 0