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

Add Binary

时间:2015-06-29 17:06:23      阅读:101      评论: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 aLen = a.size();
        int bLen = b.size();
        int i = aLen-1;
        int j = bLen-1;
        int c = 0;
        int num;
        string result;
        while(i>=0&&j>=0)
        {
            num = a[i]-‘0‘+b[j]-‘0‘+c;
            c = num/2;
            num = num%2;
            result = char(num+‘0‘)+result;//此处的想法比较关键,用一个字符串的加法从后向前添加字符。
            i--;
            j--;
        }
        while(i>=0)
        {
            num = char(a[i]-‘0‘)+c;
            c = num/2;
            num=num%2;
            result = char(num+‘0‘)+result;
            i--;
        }
        while(j>=0)
        {
            num =b[j]-‘0‘+c;
            c = num/2;
            num=num%2;
            result = char(num+‘0‘)+result;
            j--;
        }
        if(c>0)
        {
            result = ‘1‘+result;
        }
        return result;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

Add Binary

标签:

原文地址:http://blog.csdn.net/leosha/article/details/46683305

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