Leetcode#67 Add Binary

原题地址

 

简单模拟题

 

代码:

 1 string addBinary(string a, string b) {
 2         int i = a.length() - 1;
 3         int j = b.length() - 1;
 4         int carry = 0;
 5         string sum;
 6         
 7         while (i >= 0 && j >= 0) {
 8             sum += ((a[i] - '0') + (b[j] - '0') + carry) % 2 + '0';
 9             carry = ((a[i] - '0') + (b[j] - '0') + carry) / 2;
10             i--;
11             j--;
12         }
13         
14         while (i >= 0) {
15             sum += ((a[i] - '0') + carry) % 2 + '0';
16             carry = ((a[i] - '0') + carry) / 2;
17             i--;
18         }
19         
20         while (j >= 0) {
21             sum += ((b[j] - '0') + carry) % 2 + '0';
22             carry = ((b[j] - '0') + carry) / 2;
23             j--;
24         }
25         
26         if (carry > 0)
27             sum += '1';
28         
29         i = 0;
30         while (i * 2 < sum.length()) {
31             swap(sum[i], sum[sum.length() - 1 - i]);
32             i++;
33         }
34         
35         return sum;
36 }

 

posted @ 2015-02-02 09:43  李舜阳  阅读(158)  评论(0)    收藏  举报