67.二进制求和

class Solution {
    public String addBinary(String a, String b) {
        List list = new LinkedList<>();
        int len = Math.min(a.length(), b.length());
        int index = 0, temp = 0;
        while(index < len){
            int ca = a.charAt(a.length() - 1- index) - 48;
            int cb = b.charAt(b.length() - 1- index) - 48;
            index++;
            if(ca + cb + temp >= 2){ //需要进位
                list.add((ca + cb + temp) % 2);
                temp = 1;
            } else {
                list.add(ca + cb + temp);
                temp = 0;
            }
        }
        while (index < a.length()){
            int ca = a.charAt(a.length() - 1- index) - 48;
            index++;
            if(ca  + temp >= 2){ //需要进位
                list.add((ca + temp) % 2);
                temp = 1;
            } else {
                list.add(ca + temp);
                temp = 0;
            }
        }
        while (index < b.length() ){
            int cb = b.charAt(b.length() - 1- index) - 48;
            index++;
            if(cb  + temp >= 2){ //需要进位
                list.add((cb + temp) % 2);
                temp = 1;
            } else {
                list.add(cb + temp);
                temp = 0;
            }
        }
        if(temp == 1){
            list.add(temp);
        }
        StringBuilder sb = new StringBuilder();
        for(int i = list.size()-1; i >=0; i--){
            sb.append(list.get(i));
        }
        return sb.toString();
    }
}

你可能感兴趣的:(67.二进制求和)