67. 二進制求和 java

class Solution {
    public String addBinary(String a, String b) {
        int i=a.length()-1, j=b.length()-1, flag = 0;
        String result = "";
        while( i>=0 && j>=0 ) {
            int temp = (a.charAt(i--)-'0') + (b.charAt(j--)-'0') + flag;
            result += temp % 2 + "";
            flag = temp / 2;
        }
        while(i>=0) {
            int temp = (a.charAt(i--)-'0') + flag;
            result += temp % 2 + "";
            flag = temp / 2;
        }
        while(j>=0) {
            int temp = (b.charAt(j--)-'0') + flag;
            result += temp % 2 + "";
            flag = temp / 2;
        }
        if(flag == 1) result += "1";
        return new StringBuffer(result).reverse().toString();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章