今天在论坛上闲逛的时候发现了一个有趣的面试题:
帖子链接于:http://topic.csdn.net/u/20120206/09/8f62e143-aed8-4599-92df-7f4f12274e77.html
就第二个问题详细探讨:
100个整数组成的数组,打乱次序,拿掉其中一个数,把它找出来
我的思路和论坛上很多人的一样,累加求差,但是4楼这位朋友给出的答案很亮,异或运算着实让我费解了半天,还好23楼给出了解释:
打乱次序了也可以异或,A^B^C^A^B=C
本着实践出真知的求实精神,我重写了一遍程序,并验证了结果:
//100个整数组成的数组,打乱次序,拿掉其中一个数,把它找出来
#include <iostream>
using namespace std;
const int SIZE = 100;
int findLostNumber(const int *src1, const int *src2, int size);
int main()
{
int src1[SIZE], src2[SIZE];
for (int i = 0; i < SIZE; i ++)
{
src1[i] = i + 1;
src2[i] = 100 - i;
}
cout << findLostNumber(src1, src2, SIZE) << endl;
return 0;
}
//2.src1为没有缺失数的数组,src2为缺少了一个数的数组,size为没有缺失的数组的总数目
int findLostNumber(const int *src1, const int *src2, int size)
{
int lost = 0;
assert (src1 != NULL && src2 != NULL && size > 0);
for (int i = 0; i < size - 1; i ++)
{
lost ^= src1[i];
lost ^= src2[i];
}
return lost ^ src1[size - 1];
}
src1数组填充的是1-100的整数,src2数组填充的是100-1的整数,无误!
另外,4楼代码中的assert()函数引起了我的注意,它给我的第一感觉是用来判断表达式的真假,在搜索答案后发现自己的想法很接近:
assert宏的原型定义在assert.h中,其作用是如果它的条件返回错误,则终止程序执行。
详细用法参见:http://www.diybl.com/course/3_program/c++/cppjs/20071111/85534.html
呵呵,写得有点抄袭的味道,算是自己一个小小的总结吧。