码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Add Binary

时间:2015-03-18 07:48:23      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

This question is pretty straight forward.

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         int runnerA = a.size()-1, runnerB = b.size()-1, carry = 0;
 5         if (runnerA < 0) return b;
 6         if (runnerB < 0) return a;
 7         string result;
 8         while (runnerA >= 0 || runnerB >= 0) {
 9             int sum = carry;
10             if (runnerA >= 0) sum += int(a[runnerA--] - 0);
11             if (runnerB >= 0) sum += int(b[runnerB--] - 0);
12             carry = sum/2;
13             result = char(sum%2 + 0) + result;
14         }
15         if (carry) result = 1 + result;
16         return result;
17     }
18 };

 

LeetCode – Refresh – Add Binary

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4346154.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!