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

leetcode -- Add Binary

时间:2014-05-30 08:39:11      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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

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

bubuko.com,布布扣
class Solution {
public:
    string addBinary(string a, string b) {
        int MaxLen = (a.length()>b.length())?(a.length() + 1):(b.length() + 1);
        string ret(MaxLen,0);string copya(MaxLen,0);string copyb(MaxLen,0);
        int cursor = a.length()-1;
        int cursorret = MaxLen - 1;
        while(cursor >= 0)
        {copya[cursorret] = a[cursor];cursor--;cursorret--;}

        cursor = b.length()-1;cursorret = MaxLen - 1;
        while(cursor >= 0)
        {copyb[cursorret] = b[cursor];cursor--;cursorret--;}

        int p = MaxLen - 1;
        int sign = 0;
        while(p >= 0)
        {
            int tempa = copya[p] - 48;
            int tempb = copyb[p] - 48;
            int sum = tempa + tempb + sign;
            if(sum == 0) 
            {ret[p] = 0; sign = 0;}
             else if(sum == 1)
            {ret[p] = 1;sign = 0;}
             else if(sum == 2)
            {ret[p] = 0;sign = 1;}
             else if(sum == 3)
            {ret[p] = 1;sign = 1;}
             p--;
        }

        if(ret[0] == 0)
        {ret.erase(0,1);}
        return ret;
    }
};
bubuko.com,布布扣

 

leetcode -- Add Binary,布布扣,bubuko.com

leetcode -- Add Binary

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/berkeleysong/p/3756816.html

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