注:
- string转int:atoi(str.c_str())
- int转string:to_string(num)
int,long,long long取值范围:
- unsigned int 0~4294967295
- int 2147483648~2147483647
- -
- unsigned long 0~4294967295
- long 2147483648~2147483647
- -
- long long的最大值:9223372036854775807
- long long的最小值:-9223372036854775808
- unsigned long long的最大值:1844674407370955161
- -
- __int64的最大值:9223372036854775807
- __int64的最小值:-9223372036854775808
- unsigned __int64的最大值:18446744073709551615
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
做二进制加法,用string输入输出。
最开始的做法:
class Solution {
public:
string addBinary(string a, string b) {
int aa=atoi(a.c_str()),bb=atoi(b.c_str());
int a1,b1,carry=0,stay=0,sum=0,i=1;
while(aa!=0||bb!=0)
{
a1=aa%10,b1=bb%10;
aa/=10,bb/=10;
switch(a1+b1+carry)
{
case 0:
carry=0,stay=0;
break;
case 1:
carry=0,stay=1;
break;
case 2:
carry=1,stay=0;
break;
case 3:
carry=1;stay=1;
break;
}
sum+=stay*i;
i*=10;
}
sum+=carry*i;
return to_string(sum);
}
};
当测试数据为:
“1110110101”
“1110111011”
时,
运行结果为:
“-1783791888”
正确结果应为:
“11101110000”
超出int型数据范围,出错。
oh shit,数据范围的点都没有提前想到,感觉自己好愚蠢。
换个思路,全程拿string来做,毕竟a和b也有可能超长。
class Solution {
public:
string addBinary(string a, string b) {
int asize=a.size(),bsize=b.size();
int aa,bb,stay=0,carry=0;
string sum;
while(asize>0||bsize>0)
{
aa=a[asize-1]-'0',bb=b[bsize-1]-'0';
if(asize<=0) aa=0;
if(bsize<=0) bb=0;
switch(aa+bb+carry)
{
case 0:
carry=0,stay=0;
break;
case 1:
carry=0,stay=1;
break;
case 2:
carry=1,stay=0;
break;
case 3:
carry=1;stay=1;
break;
}
sum=to_string(stay)+sum;
asize--,bsize--;
}
if(carry)
sum=to_string(carry)+sum;
return sum;
}
};
当然……这里实际上并没有必要拿switch来做……
用switch代码看起来好臃肿……
不过回忆下语法也是欧凯的。
Discuss里面的Short code by c++看起来漂亮很多~
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;
}
};