首页 > 其他 > 详细

leetcode -- Add Binary

时间:2014-05-30 08:38:45      阅读:451      评论:0      收藏:0      [点我收藏+]

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

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

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