[哈希&&模拟]Happy Number uva10591
2014-02-07 09:48
204 查看
Problem C | Happy Number |
Time Limit | 1 Second |
Let the sum of the square of the digits of a positive integer S0 be represented by S1. In a similar way, let the sum of the squares of the digits ofS1 be represented
by S2 and so on. If Si = 1 for some i ³ 1, then the original integer S0 is said to be Happy number. A number, which is not happy, is called Unhappy number.
For example 7 is a Happy number since 7 -> 49 -> 97 -> 130 -> 10 -> 1 and 4 is an Unhappy number since 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4.
Input
The input consists of several test cases, the number of which you are given in the first line of the input. Each test case consists of one line containing a single positive integer N smaller than 109.
Output
For each test case, you must print one of the following messages:
Case #p: N is a Happy number.
Case #p: N is an Unhappy number.
Here p stands for the case number (starting from 1). You should print the first message if the number N is a happy number. Otherwise, print the second line.
Sample Input | Output for Sample Input |
3 7 4 13 | Case #1: 7 is a Happy number. Case #2: 4 is an Unhappy number. Case #3: 13 is a Happy number. |
Problemsetter: Mohammed Shamsul Alam
International Islamic University Chittagong
Special thanks to Muhammad Abul Hasan
一道直接可以模拟的哈希的水题,注意happy number的最大值不超过9*81。开的哈希数组1000就够用。
#include<iostream>
#include<cstring>
using namespace std;
int tag[1000];
int Happy(int num)
{
int sum=0;
while(num!=0)
{
sum=sum+(num%10)*(num%10);
num=num/10;
}
return sum;
}
int main()
{
int n,m;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>m;
memset(tag,0,sizeof(tag));
int flag=0;
int s=Happy(m);
while(tag[s]==0)
{
if(s==1)
{
flag=1;
break;
}
tag[s]=1;
s=Happy(s);
}
cout<<"Case #"<<i<<": "<<m<<" is";
if(flag==1) cout<<" a Happy number."<<endl;
else cout<<" an Unhappy number."<<endl;
}
return 0;
}
相关文章推荐
- SGU 476 Coach's Trouble 大数模拟
- hdoj 幸福列车 1434 (模拟&队列)
- POJ3087《Shuffle'm Up》方法:模拟
- ACM学习历程—ZOJ3878 Convert QWERTY to Dvorak(Hash && 模拟)
- 设计模式 --> 代理模式(二)(源码模拟改进)
- [分块][哈希] [Romanian IOI 2017 Selection #6] Jolteon && [LOJ #6187] Odd
- Delphi&C#代码模拟“显示桌面”的功能
- POJ 3295 Tautology(似乎是模拟?…
- POJ 3344 & HDU 2414 Chessboard Dance(模拟)
- (蓝桥杯模拟)1.算年龄 & 4.字符串比较(填空) & 5.还款计算
- zoj Count the Colors 1610 (数组模拟&&线段树)好题
- POJ2996 & POJ2993 (模拟)
- 【学习点滴-数据结构-栈&队列】 用两个栈模拟一个队列
- hdu--5128--计算几何<算不上.暴力模拟> && hdu--5131--初级cmp
- HDU2532 && BNU6657:Engine(模拟)
- hdoj 无限的路 2073 (数学模拟&预处理&转换)
- 【ZJOI2012】波浪 &【NOIP2017模拟9.2A组】赤壁情
- hdu4393 Throw nails【优先队列&&贪心&&模拟】
- 2017CCPC秦皇岛 A题Balloon Robot&&ZOJ3981【模拟】