Add Binary - LeetCode

题目链接

Add Binary - LeetCode

注意点

  • 考虑开头数字有进位的情况
  • 如何将string和int之间转化

解法

解法一:carry表示当前是否有进位,从尾部开始逐位相加。时间复杂度O(n)

class Solution {
public:
    string addBinary(string a, string b) {
        string ret = "";
        int i = a.length()-1,j = b.length()-1;
        int carry = 0;
        while(i >= 0 && j >= 0)
        {
            int temp = (a[i]+b[j]+carry)-96;
            if(temp>= 2) carry = 1;
            else carry = 0;
            ret = to_string(temp%2)+ret;
            i--;
            j--;
        }
        while(i >= 0)
        {
            int temp = (a[i]+carry)-48;
            if(temp >= 2) carry = 1;
            else carry = 0;
            ret = to_string(temp%2)+ret;
            i--;
        }
        while(j >= 0)
        {
            int temp = (b[j]+carry)-48;
            if(temp >= 2) carry = 1;
            else carry = 0;
            ret = to_string(temp%2)+ret;
            j--;
        }
        if(carry == 1) ret = "1"+ret;
        return ret;
    }
};

解法二:解法一中to_string效率太低了,仔细思考会发现其实真正可能出现的数字只有4个:0、1、2、3,所以就自己写个函数实现。时间复杂度O(n)

class Solution {
public:
    char toChar(int num)
    {
        if(num == 0) return '0';
        else if(num == 1) return '1';
        else if(num == 2) return '0';
        else if(num == 3) return '1';
        return '0';
    }
    string addBinary(string a, string b) {
        string ret = "";
        int i = a.length()-1,j = b.length()-1;
        int carry = 0;
        while(i >= 0 && j >= 0)
        {
            int temp = (a[i]+b[j]+carry)-96;
            if(temp>= 2) carry = 1;
            else carry = 0;
            ret.insert(ret.begin(),toChar(temp));
            i--;
            j--;
        }
        while(i >= 0)
        {
            int temp = (a[i]+carry)-48;
            if(temp >= 2) carry = 1;
            else carry = 0;
            ret.insert(ret.begin(),toChar(temp));
            i--;
        }
        while(j >= 0)
        {
            int temp = (b[j]+carry)-48;
            if(temp >= 2) carry = 1;
            else carry = 0;
            ret.insert(ret.begin(),toChar(temp));
            j--;
        }
        if(carry == 1) ret = "1"+ret;
        return ret;
    }
};

小结

  • 模拟的思想,模拟手工加法的过程。

猜你喜欢

转载自www.cnblogs.com/multhree/p/10363021.html
今日推荐