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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
表示我来过!
[***.240.166.169]2024年04月14日 02时56分23秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
你要的微信小程序终于来了
2019-05-01
有了这些 Chrome 插件,效率提升10倍(建议收藏)
2019-05-01
只有1%的程序员搞懂过浮点数陷阱
2019-05-01
一名 Google 工程师的大数据处理经验
2019-05-01
命名难,难于上青天
2019-05-01
没钱没公司,怎么做一款付费产品
2019-05-01
代码整洁之道-编写 Pythonic 代码
2019-05-01
树莓派程序开机自启动
2019-05-01
连锁门店无线通信方案
2019-05-01
配置Lotus Domino集群视频详解
2019-05-01
Linux软件万花筒
2019-05-01
全球开源软件发展趋势分析
2019-05-01
Linux常用的安全工具
2019-05-01
python 多进程之进程池的操作
2019-05-01
flask整理之 flask程序中的debug模式
2019-05-01
比特币,父母这一辈能接受吗?
2019-05-01
为什么要反对比特币,这不代表是空气币
2019-05-01
SnapEx的新感觉,对新手很友好
2019-05-01
首个聚合器怎么产生的,并运用领域在什么
2019-05-01