【LeetCode】67. Add Binary
来源:互联网 发布:高中网上听课软件 编辑:程序博客网 时间:2024/05/19 05:33
题目描述
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b ="1"
Return "100"
.
解题思路
大数相加二进制版。
先把两个数从最小位开始相加,最后把较长那个数与carry相加,直到结束。
AC代码
class Solution {public: string addBinary(string a, string b) { string ans; int carry = 0; int ai = a.size() - 1, bi = b.size() - 1; for (; ai >= 0 && bi >= 0; --ai, --bi) { int sum = (a[ai] - '0') + (b[bi] - '0') + carry; ans.push_back(sum % 2 + '0'); carry = sum / 2; } string longStr = ai < 0 ? b : a; int startIdx = ai < 0 ? bi : ai; for (; startIdx >= 0; --startIdx) { int sum = (longStr[startIdx] - '0') + carry; ans.push_back(sum % 2 + '0'); carry = sum / 2; } if (carry != 0) ans.push_back(carry + '0'); reverse(ans.begin(), ans.end()); return ans; }};
0 0
- [LeetCode]67.Add Binary
- LeetCode --- 67. Add Binary
- [Leetcode] 67. Add Binary
- [leetcode] 67.Add Binary
- 【leetcode】67. Add Binary
- [leetcode] 67.Add Binary
- [leetcode] 67. Add Binary
- 【Leetcode】67. Add Binary
- 67. Add Binary LeetCode
- 【LeetCode】67. Add Binary
- leetcode--67. Add Binary
- leetcode 67. Add Binary
- LeetCode 67. Add Binary
- LeetCode *** 67. Add Binary
- leetcode 67. Add Binary
- 【leetcode】67.Add Binary
- LeetCode 67. Add Binary
- LeetCode-67.Add Binary
- 华为机试-迷宫问题
- 先锋机器人学习笔记_1-9 使用Client对机器人实现远程控制
- Oracle 11gR2 RAC安装Part2:GI安装
- 【COGS272】【NOI1998】免费馅饼(dp)
- cocos2d-x 切换骨骼动画时残影问题
- 【LeetCode】67. Add Binary
- 程序化广告入门
- linux od 命令:按不同进制显示文件
- Linux平台 Oracle 11gR2 RAC安装Part3:DB安装
- mac上TK Framework double implementation
- 数据结构与算法之查找
- Android studio 2.2 使用 cmake 编译 libpng
- call by value or reference
- 238. Product of Array Except Self C语言