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

【leetcode】Add Binary

时间:2015-01-27 00:30:35      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

Add Binary 

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

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

 

Hide Tags
  Math String
 
 
先补全字符串,从末尾开始加,每次计算当前位和进位即可
 1 class Solution {
 2 public:
 3     char addBit(char a,char b,char &c)
 4     {
 5         if(a==b&&a==1)
 6         {
 7             char ret;
 8             ret=c;
 9             c=1;
10             return ret;
11         }
12         else if(a==b&&a==0)
13         {
14             
15             if(c==0)
16             {
17                 return 0;
18             }
19             else
20             {
21                 c=0;
22                 return 1;
23             }
24         }
25         else
26         {
27             if(c==1)
28                return 0;
29             else
30                return 1;
31             
32         }
33     }
34     
35     string addBinary(string a, string b) {
36         
37         int na=a.length()-1;
38         int nb=b.length()-1;
39         
40         if(na!=nb)
41         {
42             string tmp(abs(na-nb),0);
43             if(na>nb)
44                 b=tmp+b;
45             else
46                 a=tmp+a;
47         }
48         
49         int i=a.length()-1;
50         string result(a.length(), 1);
51         char c=0;
52         
53         while(i>=0)
54         {
55             result[i]=addBit(a[i],b[i],c);
56             i--;
57         }
58         if(c==0)
59         {
60             return result;
61         }
62         else
63         {
64             return 1+result;
65         }
66     }
67 };

 

 

【leetcode】Add Binary

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4251647.html

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