题目要求:将两个二进制字符串相加结果以二进制字符串的形式返回
要格外注意可能会在最高位存在进位

/**
 * @author rale
 * 
 * Given two binary strings, return their sum (also a binary string).
 * For example,
 * a = "11"
 * b = "1"
 * Return "100".
 */
public class AddBinary {
    
    public String addBinary(String a, String b) {
        StringBuilder result = new StringBuilder();
        int pointerA = a.length()-1;
        int pointerB = b.length()-1;
        int carry = 0;
        while(pointerA>=0 || pointerB>=0){
            int sum = carry;
            if(pointerA>=0){
                sum += (a.charAt(pointerA)-'0');
                pointerA--;
            }
            if(pointerB>=0){
                sum += (b.charAt(pointerB)-'0');
                pointerB--;
            }
            result.append(sum%2);
            carry = sum/2;
        }
        if(carry!=0){
            result.append('1');
        }
        return result.reverse().toString();
    }
}

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~


raledong
2.7k 声望2k 粉丝

心怀远方,负重前行