67. Add Binary

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

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

 

字符串表示二进制数,求相加后的结果

 

C++(6ms):

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         string res = "" ;
 5         int c = 0 ;
 6         int i = a.size()-1 ;
 7         int j = b.size()-1 ;
 8         while(i >= 0 || j >= 0 || c == 1 ){
 9             c += i >= 0 ? a[i--]-'0':0 ;
10             c += j >= 0 ? b[j--]-'0':0 ;
11             res = char(c%2 + '0') + res ;
12             c /= 2 ;
13         }
14         return res ;
15     }
16 };

 

posted @ 2017-10-14 16:23  __Meng  阅读(173)  评论(0编辑  收藏  举报