闲来无事,搜集一些有趣的面试题,以及解决方案,有些代码可能会自己写,
有些网上有比较完整的方案了,就直接把代码拷贝过来,描述一下解题思路。
Given two binary strings, return their sum (also a binary string).For example,
a = "11"
b = "1"
Return "100
"
.
这个问题比较简单,跟普通加法其实差不多,需要考虑的是进位,加法的话需要从低位开始
往高位加,这样的话,需要先将字符串反转一下,再开始加。下面是网上找来的C++代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 string addBinary(string a, string b) 6 { 7 if(a.empty()) return b; 8 if(b.empty()) return a; 9 reverse(a.begin(),a.end()); 10 reverse(b.begin(),b.end()); 11 int carry = 0; 12 string result; 13 for(int i = 0; i < max(a.size(),b.size());++i) 14 { 15 int aval = (i < a.size())?(a[i] - '0'):0; 16 int bval = (i < b.size())?(b[i] - '0'):0; 17 int sum = (aval + bval + carry)%2; 18 carry = (aval + bval + carry)/2; 19 result.insert(result.begin(),'0'+sum); 20 } 21 if(carry == 1) 22 { 23 result.insert(result.begin(),'1'); 24 } 25 return result; 26 } 27 int main(){ 28 string a = "11"; 29 string b = "1"; 30 string result = addBinary(a,b); 31 cout<<result<<endl; 32 return 0; 33 }