实现二进制加法运算:
#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;