67. Add Binary

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

Example

a = 11

b = 1

Return 100

分析:

这个和10进制加法一样。

total = a + b + carryover;

digit = total % 2;

carryover = total / 2;

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

        int aIndex = a.length() - 1;
        int bIndex = b.length() - 1;
        int carryover = 0;
        StringBuilder sb = new StringBuilder();

        while(aIndex >= 0 || bIndex >= 0 || carryover != 0) {
            
            int aValue = aIndex >= 0 ? a.charAt(aIndex) - '0' : 0;
            int bValue = bIndex >= 0 ? b.charAt(bIndex) - '0' : 0;

            int sum = aValue + bValue + carryover;
            sb.insert(0, sum % 2);
            carryover = sum / 2;
            aIndex--;
            bIndex--;
        }
        return sb.toString();
    }
}

 

posted @ 2016-07-10 23:51  北叶青藤  阅读(163)  评论(0编辑  收藏  举报