给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。
示例 1:
输入: a = “11”, b = “1”
输出: “100”
示例 2:
输入: a = “1010”, b = “1011”
输出: “10101”
提示:
每个字符串仅由字符 '0' 或 '1' 组成。
1 <= a.length, b.length <= 10^4
字符串如果不是 "0" ,就都不含前导零。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-binary
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二进制高精度加法
#define debug
#ifdef debug
#include <time.h>
#include "/home/majiao/mb.h"
#endif
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#define MAXN ((int)1e5+7)
#define ll long long int
#define QAQ (0)
using namespace std;
#define num(x) (x-'0')
#define show(x...) \
do { \
cout << "\033[31;1m " << #x << " -> "; \
err(x); \
} while (0)
void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
#define mod 2
class Solution {
public:
string addBinary(string a, string b) {
bool flag = 0;
std::reverse(a.begin(), a.end());
std::reverse(b.begin(), b.end());
string ret = "";
int n = a.length(), m = b.length(), i = 0;
for(i=0; i<n && i<m; i++) {
int tsum = num(a[i]) + num(b[i]) + flag;
flag = tsum>>1;
tsum &= 1;
ret.push_back(tsum+'0');
}
while(i < n) {
int tsum = num(a[i]) + flag;
flag = tsum>>1;
tsum &= 1;
ret.push_back(tsum+'0');
i ++;
}
while(i < m) {
int tsum = num(b[i]) + flag;
flag = tsum>>1;
tsum &= 1;
ret.push_back(tsum+'0');
i ++;
}
if(flag) ret.push_back('1');
std::reverse(ret.begin(), ret.end());
return ret;
}
};
#ifdef debug
signed main() {
freopen("test", "r", stdin);
clock_t stime = clock();
Solution s;
string a = "11", b = "1";
cout << s.addBinary(a, b);
clock_t etime = clock();
printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
return 0;
}
#endif