UVA 10591 Happy Number

大意略。。

思路:照着模拟,然后用STL容器判断是否出现过即可。

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
using namespace std;

typedef long long LL;

set<int> vis;

int n;

void init()
{
	vis.clear();
}

LL cal(int n)
{
	LL s = 0;
	while(n)
	{
		int b = n % 10;
		s += LL(b*b);
		n /= 10;
	}
	return s;
}

void solve()
{
	init();
	scanf("%d", &n);
	LL st = (int)n;
	for(;;)
	{
		if(vis.find(st) != vis.end() && st == 1) { printf("%d is a Happy number.\n", n);  break;}
		else if(vis.find(st) != vis.end() && st != 1) { printf("%d is an Unhappy number.\n", n); break; }
		vis.insert(st);
		st = cal(st);
	}
}

int main()
{
	int T, times = 0;
	scanf("%d", &T);
	while(T--)
	{
		printf("Case #%d: ", ++times);
		solve();
	}
	return 0;
}


你可能感兴趣的:(UVA 10591 Happy Number)