首页 > 其他 > 详细

Add Binary

时间:2015-11-28 06:30:34      阅读:232      评论:0      收藏:0      [点我收藏+]

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 aSize = a.size();
        int bSize = b.size();
        int len = aSize>bSize?aSize+1:bSize+1;
        string res(len,0);
        int k = len-1;
        int c = 0;
        int i=aSize-1,j=bSize-1;
        for(;i>=0 && j>=0;i--,j--){
            int tmp = ((a[i]-0) + (b[j]-0) + c )%2;
            c  = ((a[i]-0) + (b[j]-0) + c )/2;
            res[k--] = tmp+0;
        }
        while(i>=0){
            int tmp = ((a[i]-0) + c )%2;
            c  = ((a[i]-0) + c )/2;
            res[k--] = tmp+0;
            i--;
        }
        while(j>=0){
            int tmp = ((b[j]-0) + c )%2;
            c  = ((b[j]-0) + c )/2;
            res[k--] = tmp+0;
            j--;
        }
        if(c!=0){
            res[k] = c+0;
        }else{
            res.erase(res.begin(),res.begin()+k+1);
        }
        
        return res;
    }
};

 

Add Binary

原文:http://www.cnblogs.com/zengzy/p/5002092.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!