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

Leetcode Add Binary

时间:2014-06-26 15:52:27      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   color   string   

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

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

class Solution {
public:
    string addBinary(string a, string b) {
        int carry = 0, alen = a.length(),blen = b.length();
        string res="";
        if(alen > blen) {b=string(alen-blen,0)+b;blen = alen;}
        if(alen < blen) {a=string(blen-alen,0)+a;alen = blen;}
        for(int i = alen-1; i>=0 ; -- i){
            int num =(a[i]-0)+(b[i]-0)+carry;
            carry = 0;
            if(num >= 2) {num-=2;carry=1;}
            res+=0+num;
        }
        if(carry) res+=1;
        reverse(res.begin(),res.end());
        return res;
    }
};

 

Leetcode Add Binary,布布扣,bubuko.com

Leetcode Add Binary

标签:style   class   blog   code   color   string   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3808949.html

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