首页 > 其他 > 详细

Leetcode_Add Binary

时间:2014-08-05 09:43:29      阅读:258      评论: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) {
                size_t  na = a.size();
        int  nb = b.size();
        int n = na > nb ? na : nb;
        
        string result(n,'0');
        int  ch= 0;
        int i= n-1,ia=na-1,ib=nb-1;
        for(;ia >=0 && ib >= 0; ){
            int re = a[ia]-'0'+b[ib]-'0' + ch;
            ch=re/2;
            result[i]=re%2+'0';
            ia--;
            ib--;
            i--;
        }
        //int re  = a[0]+b[0]-'0'+'0'+ch;
        while(ia >=0){
           int re = a[ia]-'0' +ch;
           ch = re/2;
           result[i] = re%2+'0';
           ia--;
           i--;

        }
        
        while(ib >=0){
            int re = b[ib]-'0'+ch;
            ch = re/2;
            ib--;
            result[i]= re%2+'0';

            i--;
        }
      
        if(ch){
            result.insert(0,"1");
        }
      
        return result;
    }
};

Leetcode_Add Binary,布布扣,bubuko.com

Leetcode_Add Binary

原文:http://blog.csdn.net/qq112928/article/details/38377267

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