Add Binary--LeetCode
来源:互联网 发布:女性求职歧视知乎 编辑:程序博客网 时间:2024/06/08 16:36
1.题目
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
2.题意
给定两个二进制字符串,返回它们的总和 (也是二进制字符串)
3.分析
从尾到头遍历字符串
每次取出1个字符,转为数字,若无字符则按0处理
定义进位carry,初始值为0
将三者加起来,对2取余即为当前位的数字,对2取商即为进位的值
注意return时候,carry千万不要遗漏,如果carry为1,要在结果最前面加上1
4.代码
class Solution {public: string addBinary(string a, string b) { string res = ""; int m = a.size() - 1; int n = b.size() - 1; int carry = 0; while(m >=0 || n >= 0) { int p = m >= 0 ? a[m--] - '0' : 0; int q = n >= 0 ? b[n--] - '0' : 0; int sum = p + q + carry; res = to_string(sum % 2) + res; carry = sum / 2; } return (carry == 0) ? res : "1" + res; }};
阅读全文
0 0
- LeetCode: Add Binary
- [Leetcode] Add Binary
- LeetCode Add Binary
- Leetcode: Add Binary
- [Leetcode] Add Binary
- LeetCode : Add Binary
- LeetCode Add Binary
- [LeetCode] Add Binary
- leetcode 58: Add Binary
- leetcode Add Binary
- [LeetCode] Add Binary
- 【leetcode】Add Binary
- [LeetCode]Add Binary
- [leetcode]Add Binary
- LeetCode-Add Binary
- [leetcode] Add Binary
- LeetCode - Add Binary
- leetcode:Add Binary
- hbase行健设计原则
- BZOJ 1907 树的路径覆盖
- Android 监听多击事件
- 浅谈 Python 的 with 语句
- (M)DFS:109. Convert Sorted List to Binary Search Tree
- Add Binary--LeetCode
- mongodb 学习四(查询实战部分)MongoDB嵌套查询
- Cannot run compiler 'cl'. Maybe you forgot to setup the environment?
- Python中变量和数据类型
- MVP的简单登录
- 顺序表
- pads破解
- Docker终极指南
- redis简介及安装(集群)