Add Binary

Given two String representing two binary numbers, return their sum which should also be represented in binary string form.

e.g : "100", "111"   ->   "1011"

Solution:

1. it is similar to the decimal addition of two number. we can add them from the minimum significant bit and use (bit1+bit2+toAdd)%2 as the new number of that bit and (bit1+bit2+toAdd)/2 as new toAdd variable.

2. Once one number is wholely scanned, we scan the other string solely.

3. Once they are both scanned over, if the toAdd variable is not 0, we put it to the result and return the result.

Code:

public class Solution {
    public String addBinary(String a, String b) {
        int len_a = a.length()-1, len_b = b.length()-1;
    StringBuilder result = new StringBuilder();
    int to_add = 0;
    while(len_a>=0 && len_b>=0){
        int sum = a.charAt(len_a)-'0'+b.charAt(len_b)-'0'+to_add;
        result.insert(0,sum%2);
        to_add=sum/2;
        len_a--;
        len_b--;
    }
    while(len_a>=0){
        int sum = a.charAt(len_a)-'0'+to_add;
        result.insert(0,sum%2);
        to_add=sum/2;
        len_a--;
    }
    while(len_b>=0){
        int sum = b.charAt(len_b)-'0'+to_add;
        result.insert(0,sum%2);
        to_add=sum/2;
        len_b--;
    }
    if(to_add!=0)
        result.insert(0, to_add);
    return result.toString();
    }
}
View Code

 

posted @ 2017-06-22 02:50  小风约定  阅读(70)  评论(0)    收藏  举报