首页 > 其他 > 详细

LeetCode--Add Binary

时间:2015-01-12 17:42:02      阅读:249      评论: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 m = a.length();
        int n = b.length();
        if(m == 0)
            return b;
        if(n == 0)
            return a;
        if(n>m)
            return addBinary(b,a);
        n--;
        m--;
        string res="";
        int count = 0;
        while(n>=0 && m>=0)
        {
            int a_int = a[m]-48;
            int b_int = b[n]-48;
            int cal = count+a_int+b_int;
            count = cal/2;
            cal = cal%2;
            res += (char)(cal+48);
            m--;
            n--;
        }
        while(m>=0)
        {
            int a_int = a[m]-48;
            int cal = count+a_int;
            count = cal/2;
            cal = cal%2;
            res += (char)(cal+48);
            m--;
        }
        while(count>0)
        {
            res += (char)(count%2 + 48);
            count = count/2;
        }
        n = res.length()-1;
        int i=0;
        while(i<n)
        {
            char t = res[i];
            res[i] = res[n];
            res[n] = t;
            i++;
            n--;
        }
        return res;
    }
};


LeetCode--Add Binary

原文:http://blog.csdn.net/shaya118/article/details/42644209

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