LeetCode C++ 67. Add Binary【String】简单
发布日期:2021-07-01 02:52:56 浏览次数:2 分类:技术文章

本文共 1075 字,大约阅读时间需要 3 分钟。

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"

Constraints:

  • Each string consists only of '0' or '1' characters.
  • 1 <= a.length, b.length <= 10^4
  • Each string is either "0" or doesn’t contain any leading zero.

题意:给出两个二进制字符串,返回它们的和(用二进制表示)。


思路

LeetCode 2. Add Two Numbers 完全一致:

class Solution {
public: string addBinary(string a, string b) {
string c; int n = a.size(), m = b.size(), i = n - 1, j = m - 1, carry = 0; while (i >= 0 || j >= 0) {
int sum = carry; if (i >= 0) {
sum += a[i] - '0'; --i; } if (j >= 0) {
sum += b[j] - '0'; --j; }; c.push_back(sum % 2 + '0'); carry = sum / 2; } if (carry) c.push_back(carry + '0'); reverse(c.begin(), c.end()); return c; }};

效率如下:

执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户内存消耗:6.2 MB, 在所有 C++ 提交中击败了98.07% 的用户

转载地址:https://memcpy0.blog.csdn.net/article/details/108916150 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode C++ 129. Sum Root to Leaf Numbers【Tree/DFS】中等
下一篇:LeetCode C++ 409. Longest Palindrome【String/Hash Table】简单

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月14日 02时56分23秒