标签:bsp add bit 题目 over height 处理 class size
题目:
解答:
学习下这种思路,尤其是对最后一次进位的处理。
1 class Solution { 2 public: 3 string addBinary(string a, string b) 4 { 5 int la = a.size(); 6 int lb = b.size(); 7 8 string sum = la > lb ? a : b; 9 int overflow = 0; 10 11 for (int i = 0; i < sum.size(); i++) 12 { 13 char ca = i < la ? a[la - i - 1] : ‘0‘; 14 char cb = i < lb ? b[lb - i - 1] : ‘0‘; 15 int bit = ca - ‘0‘ + cb - ‘0‘ + overflow; 16 overflow = bit / 2; 17 sum[sum.size() - i - 1] = bit % 2 + ‘0‘; 18 } 19 20 if (overflow) 21 { 22 sum = ‘1‘ + sum; 23 } 24 25 return sum; 26 27 } 28 };
标签:bsp add bit 题目 over height 处理 class size
原文地址:https://www.cnblogs.com/ocpc/p/12822997.html