首页 > 其他 > 详细

Add Binary

时间:2015-06-29 17:03:32      阅读:212      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!