首页 > 其他 > 详细

[LeetCode] Add Binary

时间:2014-11-04 22:32:42      阅读:294      评论:0      收藏:0      [点我收藏+]

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

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

思路:时间复杂度O(n), 空间复杂度O(1)

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         string result;
 5         if (a.size() == 0 || b.size() == 0) {
 6             return a.size() == 0 ? b : a;
 7         }
 8         
 9         int carry  = 0;
10         int i = a.size() - 1;
11         int j = b.size() - 1;
12         while (i >= 0 || j >= 0) {
13             const int a_val = i >= 0 ? a[i--] - 0: 0;
14             const int b_val = j >= 0 ? b[j--] - 0: 0;
15             int temp_sum = a_val + b_val + carry;
16             result.push_back((temp_sum % 2) + 0);
17             carry = temp_sum / 2;
18         }
19         
20         if (carry == 1) result.push_back(1);
21         reverse(result.begin(), result.end());
22         return result;
23     }
24 };

 

[LeetCode] Add Binary

原文:http://www.cnblogs.com/vincently/p/4075005.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!