【Leetcode】Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         string ans;
 5         int carry = 0;
 6         int sum = 0;
 7         int i = a.size() - 1, j = b.size() - 1;
 8         while (!(i < 0 && j < 0)) {
 9             int ai = i >= 0 ? a[i] - '0' : 0;
10             int bj = j >= 0 ? b[j] - '0' : 0;
11             sum = ai + bj + carry;
12             ans.insert(ans.begin(), sum % 2 + '0');
13             carry = sum / 2;
14             --i, --j;
15         }
16         if (carry == 1) {
17             ans.insert(ans.begin(), '1');
18         }
19         return ans;
20     }
21 };
View Code

二进制加法模拟

posted @ 2014-03-20 12:54  小菜刷题史  阅读(357)  评论(0编辑  收藏  举报