LeetCode 67. Add Binary(二进制加)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jmspan/article/details/51469927

原题网址:https://leetcode.com/problems/add-binary/

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

For example,
a = "11"
b = "1"
Return "100".

方法一:使用字符串来表示。

public class Solution {
    private char xor(char a, char b) {
        if (a == b) return '0'; else return '1';
    }
    private char xor(char a, char b, char c) {
        return xor(xor(a,b), c);
    }
    private char and(char a, char b) {
        if (a == '1' && b == '1') return '1'; else return '0';
    }
    private char and(char a, char b, char c) {
        if (a == '1' && b == '1') return '1';
        if (a == '1' && c == '1') return '1';
        if (b == '1' && c == '1') return '1';
        return '0';
    }
    public String addBinary(String a, String b) {
        if (a.length() < b.length()) {
            String temp = a;
            a = b;
            b = temp;
        }
        char[] add = new char[a.length()+1];
        for(int i=0; i<a.length(); i++) add[i] = a.charAt(a.length()-1-i);
        add[a.length()] = '0';

        char carry = '0';
        for(int i=b.length()-1; i>=0; i--) {
            char temp = xor(add[b.length()-1-i], b.charAt(i), carry);
            carry = and(add[b.length()-1-i], b.charAt(i), carry);
            add[b.length()-1-i] = temp;
        }
        int j = b.length();
        while (carry == '1' && j<add.length) {
            char temp = xor(add[j], carry);
            carry = and(add[j], carry);
            add[j] = temp;
            j++;
        }
        StringBuilder sb = new StringBuilder();
        for(int i=add.length-1; i>=0; i--) {
            if (i==add.length-1 && add[i]=='0') continue;
            sb.append(add[i]);
        }
        return sb.toString();
    }
}

方法二:使用比特运算。

public class Solution {
    public String addBinary(String a, String b) {
        if (a.length() < b.length()) {
            String t = a;
            a = b;
            b = t;
        }
        boolean[] values = new boolean[a.length()+1];
        for(int i=0; i<a.length(); i++) {
            values[i] = a.charAt(a.length()-i-1) == '1';
        }
        boolean carry = false;
        for(int i=0; i<values.length; i++) {
            boolean abit = i<a.length()? values[i]: false;
            boolean bbit = i<b.length()? b.charAt(b.length()-i-1) == '1': false;
            values[i] = abit ^ bbit ^ carry;
            carry = (carry && abit) || (carry && bbit) || (abit && bbit);
        }

        StringBuilder sb = new StringBuilder();
        for(int i=values.length-1; i>=0; i--) {
            if (i==values.length-1 && !values[i]) continue;
            sb.append(values[i]?'1':'0');
        }
        return sb.toString();
    }
}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页