Add Binary

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

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


题目解析

1、需要考虑其中有一个字符串是空的情况

2、是a的长度是最长的,然后将结果保存在a中,这可以通过对比长度,然后进行替换即可

3、要考虑是否进位溢出的情况,如果溢出要在第一个位置插入进位。

4、字符串中插入字符的函数是

a.insert(0,1,inc+'0');
第一个参数为位置,第二个参数为个数,第三个是要插入的字符



#include <iostream>

using namespace std;

string addBinary(string a, string b) {
	if(a.size() == 0)
		return b;
	if(b.size() == 0)
		return a;

	int lenA = a.size();
	int lenB = b.size();

	if(lenA < lenB)
	{
		string temp = a;
		a = b;
		b = temp;
		lenA = a.size();
		lenB = b.size();
	}

	int inc = 0;
	for(int i=1;i<=lenB;i++)
	{
		int value = (a[lenA-i]-'0')+(b[lenB-i]-'0') + inc;
		a[lenA-i] = value%2 + '0';
		inc = value/2;
	}

	for(int j = (lenA-lenB-1);j>=0;j-- )
	{
		int value = (a[j]-'0')+inc;
		a[j] = value%2+'0';
		inc = value/2;
	}

	if(inc > 0)
		a.insert(0,1,inc+'0');

	return a;
}

int main(void)
{
	string a("111");
	string b("1111");

	string res = addBinary(a,b);

	cout << res.c_str() << endl;
	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值