Leetcode Add Binary

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

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


解题思路:

直接思路,不需要拐弯。按位加,用flag 记住是否有进位,有是1,没有是0, 用StringBuilder, 最后的结果需要将StringBuilder  reverse。


 Java code:

public String addBinary(String a, String b) {
        if(a == null || a.length() == 0) {
            return b;
        }
        if(b == null || b.length() == 0) {
            return a;
        }
        int pa = a.length()-1;
        int pb = b.length()-1;
        int flag = 0;
        StringBuilder sb = new StringBuilder();
        while(pa >= 0 || pb >= 0) {
            int va = 0, vb=0;
            if(pa >= 0){
                va = a.charAt(pa) - '0';
                pa--;
            }
            if(pb >= 0){
                vb = b.charAt(pb) - '0';
                pb--;
            }
            int sum = va + vb + flag;
            if(sum >= 2){
                sb.append(String.valueOf(sum-2));
                flag = 1;
            }else {
                flag = 0;
                sb.append(String.valueOf(sum));
            }
        }
        if(flag == 1){
            sb.append('1');
        }
        return sb.reverse().toString();
    }

Reference:

1. http://www.programcreek.com/2014/05/leetcode-add-binary-java/

 

posted @ 2015-09-22 03:21  茜茜的技术空间  阅读(708)  评论(0编辑  收藏  举报