小米-基础算法-二进制字符串求和

2019-01-28  本文已影响0人  luweicheng24

给定两个二进制字符串,返回他们的和(用二进制表示)
eg :
a = "11"
b = "1"
返回 "100"

实现:

public class Solution {
    /**
     * @param a: a number
     * @param b: a number
     * @return: the result
     */
    public String addBinary(String a, String b) {
        // write your code here
        StringBuilder result = new StringBuilder();
        char[] charA = a.toCharArray();
        char[] charB = b.toCharArray();
        int indexA = charA.length - 1;
        int indexB = charB.length - 1;
        int carry = 0;
        while (indexB >= 0 || indexA >= 0) {
            int sum = carry;
            if (indexA >= 0) sum += charA[indexA--] - '0';
            if (indexB >= 0) sum += charB[indexB--] - '0';
            int binary = sum % 2;
            result.append(binary);
            carry = sum/2;
        }
        if(carry>0){
            result.append(carry);
        }
        return result.reverse().toString();
    }
}
上一篇下一篇

猜你喜欢

热点阅读