[LeetCode]Add Binary

这个题目主要是需要处理两个数长度不一样的情况,有两个解决办法。我是采用递归,把长的那一段与carray再加。也可以把短的前面补0.

public class Solution {
    public String addBinary(String a, String b) {
        int p1 = a.length() - 1;
        int p2 = b.length() - 1;
        int carry = 0;
        String result = "";
        while (p1 >= 0 && p2 >= 0) {
            int one = a.charAt(p1) - '0';
            int two = b.charAt(p2) - '0';
            result = String.valueOf(one ^ two ^ carry) + result;
            carry = carry + one + two > 1 ? 1 : 0;
            p1 --;
            p2 --;
        }
        if (p1 >= 0)
            result = addBinary(String.valueOf(carry), a.substring(0, p1 + 1)) + result;
        else if (p2 >= 0)
            result = addBinary(String.valueOf(carry), b.substring(0, p2 + 1)) + result;
        else 
            result = carry == 1? String.valueOf(carry) + result : result;
        return result;
    }
}

 

posted @ 2015-12-02 03:16  Weizheng_Love_Coding  阅读(113)  评论(0编辑  收藏  举报