题意:将给出数各个位上的数字的平方和加起来得到新的数字,依次往下推新数字,直到得到得到数字1(Happy number)或是与之前重复的数字(unhappy number)。
利用哈希表查找判重或是直接打表,因为输入最大是10的9次方的数字,因此得出的数字最大为9*9*9 = 729。
代码一(hash 0.020s):
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
const int MaxSize = 850;
int head[MaxSize], next[MaxSize];
int solve(int n)
{
int t, sum = 0;
while(n)
{
t = n % 10;
sum += t * t;
n /= 10;
}
return sum;
}
int insert(int s, int h)
{
int u = head[h];
while(u)
{
if(h == 1)
return 1;
if(head[u] == head[s])
return 2;
u = next[u];
}
next[s] = head[h];
head[h] = s;
return 0;
}
int main()
{
#ifdef test
freopen("sample.txt", "r", stdin);
#endif
int p, n, flag, cct = 0;
scanf("%d", &p);
while(p--)
{
int rear = 2;
scanf("%d", &n);
printf("Case #%d: %d", ++cct, n);
memset(head, 0, sizeof(head));
n = solve(n);
while(1)
{
flag = insert(rear, n);
if(!flag)
{
n = solve(n);
++rear;
}
else if(flag == 1)
{
printf(" is a Happy number.\n");
break;
}
else if(flag == 2)
{
printf(" is an Unhappy number.\n");
break;
}
}
}
}
代码二(直接打表 0.008s):
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
const int MaxSize = 850;
int head[MaxSize];
int solve(int n)
{
int t, sum = 0;
while(n)
{
t = n % 10;
sum += t * t;
n /= 10;
}
return sum;
}
int insert(int n)
{
int m = n;
while(1)
{
n = solve(n);
if(n == 1)
return 1;
else if(head[n] || n == m)
return 0;
head[n] = 1;
}
return 0;
}
int main()
{
#ifdef test
freopen("sample.txt", "r", stdin);
#endif
int p, n, cct = 0;
scanf("%d", &p);
while(p--)
{
scanf("%d", &n);
printf("Case #%d: %d", ++cct, n);
memset(head, 0, sizeof(head));
if(insert(n))
printf(" is a Happy number.\n");
else
printf(" is an Unhappy number.\n");
}
}