zoukankan      html  css  js  c++  java
  • [LeetCode]34. Add Binary二进制相加

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

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

    解法:从后往前对两个string相加即可。注意将char转换为int,注意进位,注意结果顺序。

    class Solution {
    public:
        string addBinary(string a, string b) {
            int as = a.size(), bs = b.size();
            if (bs > as) return addBinary(b, a);
            int i = as - 1, j = bs - 1, carry = 0;
            string res = "";
            while (i >= 0)
            {
                int curr = (int)(a[i] - '0') + carry + (j >= 0 ? (int)(b[j] - '0') : 0);
                res += (char)(curr % 2 + '0');
                carry = curr / 2;
                i--; j--;
            }
            res = carry == 1 ? res + '1' : res;
            reverse(res.begin(), res.end());
            return res;
        }
    };

    或者直接使用string的insert成员函数:

    class Solution {
    public:
        string addBinary(string a, string b) {
            int as = a.size(), bs = b.size();
            if (bs > as) return addBinary(b, a);
            int i = as - 1, j = bs - 1, carry = 0;
            string res = "";
            while (i >= 0)
            {
                int curr = (int)(a[i] - '0') + carry + (j >= 0 ? (int)(b[j] - '0') : 0);
                res.insert(0, 1, (char)(curr % 2 + '0'));
                carry = curr / 2;
                i--; j--;
            }
            res = carry == 1 ? res.insert(0, 1, '1') : res;
            return res;
        }
    };
  • 相关阅读:
    西安.NET俱乐部群 推广代码
    跟我学Makefile(六)
    跟我学Makefile(五)
    跟我学Makefile(四)
    跟我学Makefile(三)
    跟我学Makefile(二)
    Kconfig文件说明2
    Kconfig文件说明
    kernel内核配置说明
    makefile中ifeq与ifneq dev/null和dev/zero简介 dd命令
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4903621.html
Copyright © 2011-2022 走看看