leetcode学习笔记:Add Binary

一.题目描述

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());(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;}};

测试代码:

::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;}

几个测试结果:

我们什么都没有,唯一的本钱就是青春。

leetcode学习笔记:Add Binary

相关文章:

你感兴趣的文章:

标签云: