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

leetcode - Add Binary

时间:2015-12-14 14:08:14      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

class Solution {
public:
    std::string addBinary(std::string a, std::string b) {
		int la = a.size();
		int lb = b.size();
		int len = std::min(la,lb);
		std::reverse(a.begin(),a.end());
		std::reverse(b.begin(),b.end());
		std::string c;
		int s = 0;
		for (int i = 0; i < len; i++)
		{
			s += a[i] - '0' + b[i] - '0';
			c.insert(c.begin(),s % 2 + '0');
			s /= 2;
		}
		if(la < lb)
		{
			for (int i = la; i < lb; i++)
			{
				s += b[i] - '0';
				c.insert(c.begin(),s % 2 + '0');
				s /= 2;
			}
		}
		else
		{
			for (int i = lb; i < la; i++)
			{
				s += a[i] - '0';
				c.insert(c.begin(),s % 2 + '0');
				s /= 2;
			}
		}
		if(s > 0)
		{
			c.insert(c.begin(),s + '0');
		}
#if 0
		for (int i = 0; i < c.size(); i++)
		{
			std::cout << c[i];
		}
		std::cout << std::endl;
#endif // 1

		return c;
    }
};


leetcode - Add Binary

标签:

原文地址:http://www.cnblogs.com/hrhguanli/p/5045052.html

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