20191205更新
class Solution {
public:
string addBinary(string a, string b) {
size_t siz1 = a.length();
size_t siz2 = b.length();
size_t siz;
if(siz1 < siz2){
a = string(siz2-siz1, '0') + a;
siz = siz2;
}
else{
b = string(siz1-siz2, '0') + b;
siz = siz1;
}
char c = '0';
int temp;
for(int i = siz-1; i >= 0; i--){
temp = (a[i] + b[i] + c)-('0')*3;
c = temp/2+'0';
a[i] = '0' + temp%2;
if(i == 0 && c == '1')
a = "1" + a;
}
return a;
}
};
跟之前数组的表示相比,这里每个位置只能保存一个字符’0‘或者’1‘,需要另外存储进位,而且要在char的字符和数字之间转换。
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
int len1 = a.length();
int len2 = b.length();
int len = max(len1, len2);
if(len1 < len) //这里不能有等号
a.insert(0, len-len1, '0');//补齐
else
b.insert(0, len-len2, '0');
int c = 0;//进位
for(int i = len-1; i >= 0; --i){
int temp = a[i] -'0' + b[i] - '0' + c;//int(a[i])获得的是该字符的ASCII码
if(temp%2)
a[i] = '1';//这里绝对不能是a[i]=temp%2!!!
else
a[i] = '0';
c = temp/2;
}
if(c)
a.insert(0, 1, '1');
return a;
}
};
字符转数字:s-'0' 字符就是数字
数字转字符:char(num+'0')