LeetCode 67 : Add Binary (Java)

解题思路:从末尾依次对应相加来求,转成int中的相加会使代码比较简洁,因为可以用/和%来分别求出进位和当前往结果中添加的位。然后,把较长的字符串剩下的部分和进位相加放入结果。最后,还要判断进位此时是否为1,如果为1,则需要再往结果中添加1,否则返回结果。

public class Solution {
    public String addBinary(String a, String b) {
        if(a.length() < b.length()){
            String tmp = a;
            a = b;
            b = tmp;
        }

        int pa = a.length()-1;
        int pb = b.length()-1;
        int carries = 0;
        String rst = "";

        while(pb >= 0){
            int sum = (int)(a.charAt(pa) - '0') + (int)(b.charAt(pb) - '0') + carries;
            rst = String.valueOf(sum % 2) + rst;
            carries = sum / 2;
            pa --;
            pb --;
        }

        while(pa >= 0){
            int sum = (int)(a.charAt(pa) - '0') + carries;
            rst = String.valueOf(sum % 2) + rst;
            carries = sum / 2;
            pa --;
        }       

        if (carries == 1)
            rst = "1" + rst;
        return rst;
    }
}
阅读更多

没有更多推荐了,返回首页