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

Leetcode_Add Binary

时间:2014-08-05 09:43:29      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:leetcode   数据结构   

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

标签:leetcode   数据结构   

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

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