LeetCode - 67. Add Binary(4ms)

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"
 class Solution {
public:
string addBinary(string a, string b) {
int la = a.length();
int lb = b.length();
string res = "";
int car = ;
if(la <= lb) {
for(int i = la - ; i >= ; i--) {
if(a[i] == '' && b[lb - (la - i)] == '') {
if(car == )
res = '' + res;
else {
res = '' + res;
car = ;
}
}
else if(a[i] != b[lb - (la - i)]) {
if(car == )
res = '' + res;
else
res = '' + res;
}
else {
if(car == ) {
res = '' + res;
car = ;
}
else
res = '' + res;
}
}
for(int i = lb - la - ; i >= ; i--) {
if(b[i] == '') {
if(car == )
res = '' + res;
else
res = '' + res;
}
else {
if(car == ) {
res = '' + res;
car = ;
}
else
res = '' + res;
}
}
if(car == ) {
res = '' + res;
}
return res;
}
else if(lb < la) {
for(int i = lb - ; i >= ; i--) {
if(b[i] == '' && a[la - (lb - i)] == '') {
if(car == )
res = '' + res;
else {
res = '' + res;
car = ;
}
}
else if(b[i] != a[la - (lb - i)]) {
if(car == )
res = '' + res;
else
res = '' + res;
}
else {
if(car == ) {
res = '' + res;
car = ;
}
else
res = '' + res;
}
}
for(int i = la - lb - ; i >= ; i--) {
if(a[i] == '') {
if(car == )
res = '' + res;
else
res = '' + res;
}
else {
if(car == ) {
res = '' + res;
car = ;
}
else
res = '' + res;
}
}
if(car == ) {
res = '' + res;
}
return res;
}
}
};
上一篇:leetCode 67.Add Binary (二进制加法) 解题思路和方法


下一篇:mysql-关于Unix时间戳(unix_timestamp)