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

Add Binary

时间:2014-10-18 10:56:14      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   strong   sp   div   

题目描述:

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         int LocationA = a.size() - 1;
 5         int LocationB = b.size() - 1;
 6 
 7         if (LocationA == -1) {
 8             return b;
 9         }
10         if (LocationB == -1) {
11             return a;
12         }
13         string result;
14         int carry = 0;
15 
16         while((LocationA >= 0) && (LocationB >= 0)) {
17             int temp = ((a[LocationA] - 0) + (b[LocationB] - 0) + carry) % 2;
18             carry    = ((a[LocationA] - 0) + (b[LocationB] - 0) + carry) / 2;
19             result.append(1, temp + 0);
20             --LocationA;
21             --LocationB;
22         }
23         if (LocationA != -1) {
24             while(LocationA >= 0) {
25                 int temp = ((a[LocationA] - 0) + carry) % 2;
26                 carry    = ((a[LocationA] - 0) + carry) / 2;
27                 result.append(1, temp + 0);
28                 --LocationA;
29             }
30         }
31         if (LocationB != -1) {
32             while(LocationB >= 0) {
33                 int temp = ((b[LocationB] - 0) + carry) % 2;
34                 carry    = ((b[LocationB] - 0) + carry) / 2;
35                 result.append(1, temp + 0);
36                 --LocationB;
37             }
38         }
39 
40         if (carry != 0) {
41             result.append(1, carry + 0);
42         }
43 
44         int i = 0;
45         int j = result.size() - 1;
46         //将字符串反转
47         while (i <= j) {
48             char temp = result[i];
49             result[i] = result[j];
50             result[j] = temp;
51             ++i;
52             --j;
53         }
54         return result;
55     }
56 };

 

Add Binary

标签:style   blog   color   io   ar   for   strong   sp   div   

原文地址:http://www.cnblogs.com/skycore/p/4032593.html

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