zoukankan      html  css  js  c++  java
  • Add Binary

    题目链接

    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;
        }
    };
    

    小结

    • 模拟的思想,模拟手工加法的过程。
  • 相关阅读:
    【漏洞分析】5次shift漏洞破解win7密码
    skyler实战渗透笔记(五)—Tr0ll
    skyler实战渗透笔记(四)—Raven2
    skyler实战渗透笔记(三)—Raven
    python读写excel文件
    python_列表
    mysql安装教程
    centos7安装RabbitMQ教程
    centos7安装mongodb4.2.15教程
    tomcat9安装教程
  • 原文地址:https://www.cnblogs.com/multhree/p/10363021.html
Copyright © 2011-2022 走看看