LeetCode-add-binary

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) {
        char[] ca = a.toCharArray();
        char[] cb = b.toCharArray();
        int sta = ca.length;
        int stb = cb.length;
        int addon = 0;
        char[] res = new char[Math.max(sta, stb) + 1];
        int mark = 0;
        while (sta > 0 || stb > 0 || addon != 0) {
            int t = 0;
            if (sta > 0) {
                sta--;
                t += ca[sta] - '0';
 
            }
            if (stb > 0) {
                stb--;
                t += cb[stb] - '0';
            }
            if (addon != 0) {
                t += addon;
                addon = 0;
            }
            addon = t / 2;
            t %= 2;
            char c = t == 1 ? '1' : '0';
            res[mark] = c;
            mark++;
        }
        for (int i = 0, j = mark - 1; i < j; i++, j--) {
            char c = res[i];
            res[i] = res[j];
            res[j] = c;
        }
        return new String(res).substring(0, mark);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42146769/article/details/89061539