1. 程式人生 > >Add Binary:二進位制加法

Add Binary:二進位制加法

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

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

思路:從最低位按位掃描相加,最後注意進位的處理。由於是從最低位開始,隨意最後的結果高位低位相反,要反轉一下。
class Solution {
    public String addBinary(String a, String b) {
        if(a.length()<b.length()) return addBinary(b,a);
        StringBuilder sb = new StringBuilder();
        int i = a.length()-1;//a下標
        int j = b.length()-1;//b下標
        int add = 0;//進位
        //System.out.println(a.length()-b.length() - 1);
        while(i >= 0&& j >=0){
            int x = Integer.parseInt(a.charAt(i)+"");
            int y = Integer.parseInt(b.charAt(j)+"");
            int temp = (x + y + add);
            int z = temp % 2;
            add = temp / 2;
            sb.append(z);
            i--;
            j--;
        }
        while(i>=0){
            int x = Integer.parseInt(a.charAt(i)+"");
            int temp = (x + add);
            int z = temp % 2;
            add = temp / 2;
            sb.append(z);
            i--;
        }
        if(add!=0) sb.append(1);
        return sb.reverse().toString();
    }
}