Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
与No.2 Add Two Numbers的思路非常相似,不同在:对其进行运算时,其实是要逆向相加的!!!因为边界控制的原因,可先将字符串逆序reverse( )。
1 #include "stdafx.h" 2 #include <string> 3 #include <iostream> 4 #include <algorithm> 5 class Solution 6 { 7 public: 8 string addBinary(string a, string b) 9 { 10 string result(""); 11 reverse(a.begin(),a.end());//注意运算顺序的问题!!! 12 reverse(b.begin(),b.end()); 13 14 auto ita = a.begin(); 15 auto itb = b.begin(); 16 int data1 = 0; 17 int data2 = 0; 18 int carry = 0; 19 int sum = 0; 20 21 while(ita != a.end() || itb != b.end()) 22 {//从尾向前遍历 23 data1 = 0; 24 data2 = 0; 25 if(ita != a.end()) 26 { 27 data1 = *ita -‘0‘; 28 ita++; 29 } 30 if(itb != b.end()) 31 { 32 data2 = *itb -‘0‘; 33 itb++; 34 } 35 sum = data1+data2+carry; 36 //头插 37 result.insert(result.begin(),sum%2+‘0‘);//!!!格式问题 38 carry = sum/2; 39 } 40 if(carry== 1) 41 result.insert(result.begin(),‘1‘); 42 43 return result; 44 } 45 }; 46 int main() 47 { 48 Solution sol; 49 cout << sol.addBinary(string("11"),string("1"))<<endl; 50 cout << sol.addBinary(string(""),string("1"))<<endl; 51 cout << sol.addBinary(string("111"),string("1111"))<<endl; 52 cout << sol.addBinary(string("111"),string("111"))<<endl; 53 cout << sol.addBinary(string(""),string(""))<<endl; 54 return 0; 55 }
时间: 2024-10-06 20:49:49