Add Binary 408

Question

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

Example

a = 11

b = 1

Return 100

Solution

方法一:将两个数转换成二进制整数,然后用位运算进行相加,再将所得结果用二进制string表示。

方法二:将长的那个数放在前,短的数放在后。用carriers记录进位。然后从后往前将两个数对应的位置上的数相加上carriers,将结果%2加入res之前,同时用结果/2来更新carriers。当短的数到头之后,则只要将长的数的位上的数和carriers相加即可。最后当长的数也到头之后,若carriers为1,则在res前加"1"即可。

代码如下:

方法一:

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
        int c = Integer.parseInt(a, 2);
        int d = Integer.parseInt(b, 2);
        while(d != 0){
            int _c = c ^ d;
            int _d = (c & d) << 1;
            c = _c;
            d = _d;
        }

        return Integer.toBinaryString(c);
    }
}

方法二:

public class Solution {
    public String addBinary(String a, String b) {
        if(a.length() < b.length()){
            String tmp = a;
            a = b;
            b = tmp;
        }

        int pa = a.length()-1;
        int pb = b.length()-1;
        int carries = 0;
        String rst = "";

        while(pb >= 0){
            int sum = (int)(a.charAt(pa) - '0') + (int)(b.charAt(pb) - '0') + carries;
            rst = String.valueOf(sum % 2) + rst;
            carries = sum / 2;
            pa --;
            pb --;
        }

        while(pa >= 0){
            int sum = (int)(a.charAt(pa) - '0') + carries;
            rst = String.valueOf(sum % 2) + rst;
            carries = sum / 2;
            pa --;
        }       

        if (carries == 1)
            rst = "1" + rst;
        return rst;
    }
}

results matching ""

    No results matching ""