面试题(52)|数据结构(23)写一个复数类或者大整数类,实现基本的加减乘运算,熟悉封装与数据抽象

从《C++ Primer》入手学习C++

实现二进制加法运算: 

#include <iostream>
using  namespace std;


int main()
{
    std::cout << "Hello World!\n";
	string a = "11000";
	string b = "1011";
	reverse(a.begin(), a.end());
	reverse(b.begin(), b.end());
	cout << "a:" << a.c_str() << endl;
	cout << "b:" << b.c_str() << endl;
	size_t n = a.size() > b.size() ? a.size() : b.size();
	int carry = 0;
	string res;
	for (int i = 0; i < n; i++)
	{
		int numa = i < a.size() ? a[i] - '0' : 0;
		int numb = i < b.size() ? b[i] - '0' : 0;
		int val = (numa+numb+carry) % 2;
		carry = (numa + numb + carry) / 2;
		res.insert(res.begin(), val + '0');
		cout << "res:" << res.c_str() << endl;
	}
	if (carry == 1)
		res.insert(res.begin(), '1');
	cout << "last res:" << res.c_str() << endl;
	return 0;
}

打印结果: 

a:00011
b:1101
res:1
res:11
res:011
res:0011
res:00011
last res:100011

reverse(a.begin(),a.end()):翻转字符串a

insert(res.begin(),'1')在最前面加1;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haimianjie2012

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值