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;
        }
    };
  • 相关阅读:
    Java 工程名上有个红色叹号
    TestNG 入门教程
    字典序问题
    统计数字问题
    sniffer 简介
    【转】IE浏览器快捷键大全
    批处理 延时不完全总结【转】
    批处理(Batch)---批处理脚本。
    windows系统命令行
    计算机网络
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4903621.html
Copyright © 2011-2022 走看看