题目见书《剑指offer》44页;
编程思路:将所输入数字与二维数组中的数字进行比较,如果相等则返回1,不相等则返回0,运用了遍历的思想,未用到指针。
#include <iostream>
using namespace std;
bool find(int a[4][4], int number)
{
int i, j;
bool found = false;
for (i = 0; i < 4; i++)
{
//先内而外
for (j = 0; j < 4; j++)
{
if (number != a[i][j])
{
continue; //注意这里是continue,不然遍历不到数组中除第一列以外的数组
}
else
{
found = true;
break;
}
}
}
return found;
}
int main()
{
int a[4][4] = { {1,2, 8, 9},{2 ,4, 9, 12},{4, 7, 10, 13},{6, 8, 11, 15} };
int m = 5;
bool c=find(a, m);
cout << c << endl;
system("pause");
return 0;
}
当输入数字为15时,输出为1:
当输入数字为5时,输出为0: