【LeetCode 67_字串_算術運算】Add Binary

QingLiXueShi發表於2015-07-07

 1 string addBinary(string a, string b)
 2 {
 3     int alen = a.size();
 4     int blen = b.size();
 5     if (alen == 0)
 6         return b;
 7     else if (blen == 0)
 8         return a;
 9 
10     int i = alen - 1;
11     int j = blen - 1;
12     int carry = 0;
13     string res;
14     while (i >= 0 || j >= 0 || carry > 0) {
15         if (i >= 0) 
16             carry += a[i--] - '0';
17         if (j >= 0)
18             carry += b[j--] - '0';
19         res = (char)(carry % 2 + '0') + res;        //res不用逆序處理了
20         carry = carry / 2;
21     }
22     return res;
23 }

 

相關文章