C/C++ Find the missing number

题目描述

There are five numbers 1,2,3,4 and 5,now you can see four of them,do you know what is the remaining one?

输入格式

 Four different  integers in range 1 to 5.

输出格式

 One line,the missing number.

样例输入
将样例输入复制到剪贴板
2 4 1 5
样例输出
3

代码:
#include <iostream> 
using namespace std;

int getMissNo(int a[])
{
	for(int j = 1,i = 0; j <= 5;)
	{
		if(j != a[i] && i >= 4)
		{
			return j;
		}
		if(j == a[i])
		{
			j++;
			i = 0;
		}	
		if(j != a[i] && i < 4)
			i++;
	}
}

int main()
{
	int a[4];
	for(int i = 0; i <= 3; i++)
	{
		cin>>a[i];
	}
	int miss = getMissNo(a);
	cout<<miss<<endl;
	
	return 0;
}


我这里采用的是遍历的方法,也就是先设置好一个包含1到5所有数的数组(用循环遍历的方式代替数组),让输入的数组a[]中的每一个值与之一一比较,如果发现在a[]数组所有的数中都找不到匹配,那此时遍历到的数即是丢失了的数。
posted @ 2015-11-28 23:32  Victor_Lv  阅读(129)  评论(0编辑  收藏  举报