leetcode笔记:Add Binary
来源:互联网 发布:澳洲大学申请时间 知乎 编辑:程序博客网 时间:2024/04/28 19:41
一.题目描述
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return ”100”.
二.解题技巧
这道题考察两个二进制数相加,考虑到输入的是两组string,同时注意在运算时从左到右分别是从低位到高位,因此需要考虑对输入进行翻转处理,中间二进制树相加部分没有过多的设计障碍,主要是计算进位;在两组数据相加完成后,还需要考虑最高位的进位问题。
三.示例代码
#include <iostream>#include <string>using namespace std;class Solution{public: string AddBinary(string a, string b) { size_t size = a.size() > b.size() ? a.size() : b.size(); reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); int CarryBit = 0; // 进位 string result; // 用于存放结果 for (size_t i = 0; i < size; i++) { int a_num = a.size() > i ? a[i] - '0' : 0; int b_num = b.size() > i ? b[i] - '0' : 0; int val = (a_num + b_num + CarryBit) % 2; CarryBit = (a_num + b_num + CarryBit) / 2; // 进位 result.insert(result.begin(), val + '0'); } if (CarryBit == 1) result.insert(result.begin(), '1'); return result; }};
测试代码:
#include "AddBinary.h"using std::cout;using std::cin;int main(){ string a, b; cout << "Input the first string: "; cin >> a; cout << "\nInput the second string: "; cin >> b; Solution s; string result = s.AddBinary(a, b); cout << "\nThe Add Binary result is : " << result; return 0;}
几个测试结果:
4 0
- leetcode笔记:Add Binary
- leetcode笔记--Add Binary
- LeetCode笔记:67. Add Binary
- 小白笔记---------------------------------leetcode(67. 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 58: Add Binary
- leetcode Add Binary
- [LeetCode] Add Binary
- 【leetcode】Add Binary
- [LeetCode]Add Binary
- [leetcode]Add Binary
- 九度oj 1039
- codeforces#FF DIV2C题DZY Loves Sequences(DP)
- HIbernate关系映射--单向一对多@OneToMany
- GYM 100523 I【二分图的最大点权独立集】
- exgcd求逆元模板
- leetcode笔记:Add Binary
- linux在线安装软件
- 黑马程序员Java学习笔记之正则表达式
- JS基本类型和引用类型的值
- angularjs install for window
- LRU Cache
- Java集合---List
- 数据结构——线索二叉树
- iGrimaceV8在线源安装