0
点赞
收藏
分享

微信扫一扫

剑指offer数据结构与算法002二进制加法

双井暮色 2022-03-14 阅读 56

题目简单分析

字符二进制加法,可以参考10进制加法直接计算,从低位开始取出字符相加,记录进位。
每次将计算结果添加到字符中。
c++提供字符操作函数,字符串后面可以直接用+号连接其他字符或串, (串).size()可以获得串长,这个长度不包括末尾表示符。以及reverse(串)函数反转字符串,cout<<(串)可以直接打印串。

代码

string addBinary(string a, string b){
	int Ai, Bj;
	int i = a.size()-1, j = b.size()-1;
	int carry = 0;
	int sum;
	string result="";
	while (i >= 0 || j >= 0){
		if (i >= 0)
			Ai = (int)a[i--] - '0';
		else
			Ai = 0;
		if (j >= 0)
			Bj = (int)b[j--] - '0';
		else
			Bj = 0;

		sum = Ai + Bj + carry;
		if (sum >= 2)
		{
			carry = 1;
			sum -= 2;
		}
		else
			carry = 0;
		result = result + (char)('0'+sum);
	}
	if (carry == 1)
		result =  result+'1';
	reverse(result.begin(),result.end());
	return result;
}
举报

相关推荐

0 条评论