[leetcode] Add Binary

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

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

https://oj.leetcode.com/problems/add-binary/

 

思路:类似大数计算只是进位有区别,小心carry的处理。

public class Solution {
    public String addBinary(String a, String b) {
        if (a == null || a.length() == 0)
            return b;
        if (b == null || b.length() == 0)
            return a;

        int m = a.length(), n = b.length();
        StringBuilder res = new StringBuilder();
        int i = m - 1, j = n - 1;
        int x, y, c = 0;
        while (i >= 0 || j >= 0) {
            x = (i >= 0) ? a.charAt(i) - '0' : 0;
            y = (j >= 0) ? b.charAt(j) - '0' : 0;
            res.append(x ^ y ^ c);
            c = (x + y + c >= 2) ? 1 : 0;
            i--;
            j--;
        }
        if (c == 1)
            res.append(1);

        return res.reverse().toString();

    }

    public static void main(String[] args) {
        System.out.println(new Solution().addBinary("11", "1"));
        System.out.println(new Solution().addBinary("1111", "1111"));
        System.out.println(new Solution().addBinary("11", ""));
        System.out.println(new Solution().addBinary("11111111111111111111", "1"));
        System.out.println(new Solution().addBinary("0101", "1010"));

    }
}
View Code

 

 第二遍记录:

  注意是2进制加法。

  注意倒序取数据最后翻转。

  注意用位操作简化进位。

 

posted @ 2014-06-27 18:28  jdflyfly  阅读(259)  评论(0编辑  收藏  举报