[leetcode] 67. 二进制求和

67. 二进制求和

模拟加法运算

class Solution {
    public String addBinary(String a, String b) {
        int m = a.length();
        int n = b.length();
        a = new StringBuffer(a).reverse().toString();
        b = new StringBuffer(b).reverse().toString();

        int[] ans = new int[m + n];
        int i = 0;
        for (i = 0; i < a.length() && i < b.length(); i++) {
            ans[i] = a.charAt(i) - '0' + b.charAt(i) - '0';
        }
        if (i == a.length() && i < b.length()) {
            for (int j = i; j < b.length(); j++) {
                ans[j] = b.charAt(j) - '0';
            }
        }
        if (i == b.length() && i < a.length()) {
            for (int j = i; j < a.length(); j++) {
                ans[j] = a.charAt(j) - '0';
            }
        }

        // 处理进位
        int k = 0;
        while (k < m + n - 1) {
            ans[k + 1] += ans[k] / 2;
            ans[k] %= 2;
            k++;
        }
        int top = m + n - 1;
        while (ans[top] == 0 && top > 0) {
            top--;
        }
        String s = "";
        for (int j = top; j >= 0; j--) {
            s += ans[j];
        }
        return s;
    }
}

posted @ 2018-07-24 23:50  ACBingo  阅读(192)  评论(0编辑  收藏  举报