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

    小结

    • 模拟的思想,模拟手工加法的过程。
  • 相关阅读:
    vbs获取当月的第一天和最后一天的日期
    vbscript基础篇
    win10专业版激活
    python selenium中Excel数据维护
    python里面的xlrd模块详解
    python 转换为json时候 汉字编码问题
    用VBA得到EXCEL表格中的行数和列数
    表关联关系,表的复制
    存储引擎,详细建表语句,数据类型,约束
    数据库基础
  • 原文地址:https://www.cnblogs.com/multhree/p/10363021.html
Copyright © 2011-2022 走看看