算法与数据结构之二进制数字相加
67. Add Binary
贴上代码,如何处理好进位是关键
class Solution {
public:
string addBinary(string a, string b) {
string s = "";
int c = 0, i = a.size() - 1, j = b.size() - 1;
while(i >= 0 || j >= 0 || c == 1)
{
c += i >= 0 ? a[i --] -'0' : 0;
c += j >= 0 ? b[j --]-'0' : 0;
s = char(c % 2 + '0') + s;
c /= 2;
}
return s;
}
};
char to int 用 -'0'
int to char 用+'0'
to_string()接受int参数
char*itoa(int value,char*string,int radix);
int atoi(const char *nptr);