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

LeetCode--Add Binary

时间:2015-01-12 17:43:48      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:leetcode   string   

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

标签:leetcode   string   

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

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