算法导论——2.1-4

时间:2023-02-22 23:31:03

算法导论——2.1-4


最近还找到一种方法:

#include<iostream>

using namespace std;

int main()
{
	size_t n;
	cin >> n;
	int a[4], b[4],c[5];
	cout << "input a[]:" << endl;
	for (int i = 0; i < n; ++i)
		cin >> a[i];
	cout << "input b[]:" << endl;
	for (int i = 0; i < n; ++i)
		cin >> b[i];
	for (int i = 0; i < n; ++i)
		c[i + 1] = a[i] + b[i];
	c[0] = 0;
	for (int *p = end(c); p >= begin(c); --p)
	{
		if (*p == 2)
		{
			*(p - 1) = *(p - 1) + 1;
			*p = 0;
		}
	}
	for (int *p = begin(c); p < end(c); ++p)
		cout << *p << " ";
	cout <<endl;
	return 0;
}
不过对数组长度有限制,输入的n必须和数组的初始设定的长度一样,否则数组里面的垃圾数据会影响结果。 算法导论——2.1-4