• 67. Add Binary


    Problem:

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

    The input strings are both non-empty and contains only characters 1 or 0.

    Example 1:

    Input: a = "11", b = "1"
    Output: "100"
    

    Example 2:

    Input: a = "1010", b = "1011"
    Output: "10101"
    

    思路

    Solution (C++):

    string addBinary(string a, string b) {
        int m = a.size(), n = b.size(), carry = 0, i = 0, digit = 0;
        vector<int> v;
        while (i < m && i < n) {
            digit = int(a[m-1-i]) -48 + int(b[n-1-i]) -48 + carry;
            carry = digit / 2;
            digit %= 2;
            v.push_back(digit);
            ++i;
        }
        if (i < m) {
            while (i < m) {
                digit = int(a[m-1-i]) -48 + carry;
                carry = digit / 2;
                digit %= 2;
                v.push_back(digit);
                ++i;
            }
        }
        if (i < n) {
            while (i < n) {
                digit = int(b[n-1-i]) -48 + carry;
                carry = digit / 2;
                digit %= 2;
                v.push_back(digit);
                ++i;
            }
        }
        
        if (carry == 1) v.push_back(carry);
        string res = "";
        for (int j = 0; j < v.size(); ++j) {
            res += to_string(v[v.size()-j-1]);
        }
        return res;
    }
    

    性能

    Runtime: 4 ms  Memory Usage: 6.8 MB

    思路

    Solution (C++):

    
    

    性能

    Runtime: ms  Memory Usage: MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    Azureus 3.0.0.8
    KchmViewer 3.0
    GNOME 2.18.0 正式版颁发宣布
    Emacs 22.0.95
    gTwitter:Twitter 的 Linux 客户端
    KDE DVD Authoring Wizard-易用的 DVD 制造器材
    GIMP 2.3.15
    Monit-零碎看监工具
    Cobras-专注于 Qt 的 IDE
    K3b 1.0 正式版公布
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12586331.html
Copyright © 2020-2023  润新知