题意:两个二进制数相加,大数加法的变形
大数加法流程:
1.倒置两个大数,这一步能使所有大数对齐
2.逐位相加,同时进位
3.倒置两个大数的和作为输出
1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 5 if(a.size() < b.size()){ 6 string t = a; 7 a = b; 8 b = t; 9 } //该步使的能大数加小数,使其能加 10 reverse(a.begin(),a.end()); 11 reverse(b.begin(),b.end());//倒置两数 12 for(string::size_type i = 0; i < a.size(); ++i){ 13 a[i] += ((i < b.size())? b[i] : '0') - '0';//逐位相加 14 } 15 16 for(string::size_type i = 0; i < a.size() - 1; ++i){ 17 if(a[i] >='2' ) { 18 a[i] -= 2; 19 a[i+1] ++; 20 } 21 } 22 if(a[a.size()-1] >='2' ) { 23 a[a.size()-1] -= 2; 24 a += "1"; 25 } //进位 26 reverse(a.begin(),a.end()); //倒置输出 27 return a; 28 } 29 };