Gym 101667D Happy Number(简单题)
Gym 101667D Happy Number
Description
Consider the following function ݂ defined for any natural number ݊:
݂ሺ݊ሻ is the number obtained by summing up the squares of the digits of ݊ in decimal (or base-ten).
If ݊ ൌ 19, for example, then ݂ሺ19ሻ ൌ 82 because 1ଶ 9ଶ ൌ 82.
Repeatedly applying this function ݂, some natural numbers eventually become 1. Such numbers are called happy numbers. For example, 19 is a happy number, because repeatedly applying function ݂ to 19 results in:
݂ሺ19ሻ ൌ 1ଶ 9ଶ ൌ 82
݂ሺ82ሻ ൌ 8ଶ 2ଶ ൌ 68
݂ሺ68ሻ ൌ 6ଶ 8ଶ ൌ 100
݂ሺ100ሻ ൌ 1ଶ 0ଶ 0ଶ ൌ 1
However, not all natural numbers are happy. You could try 5 and you will see that 5 is not a happy number. If is not a happy number, it has been proved by mathematicians that repeatedly applying function ݂ to ݊ reaches the following cycle:
4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.
Write a program that decides if a given natural number ݊ is a happy number or not.
Input
Your program is to read from standard input. The input consists of a single line that contains an integer, ݊
(1 ݊ 1,000,000,000)
Output
Your program is to write to standard output. Print exactly one line. If the given number ݊ is a happy number,print out HAPPY; otherwise, print out UNHAPPY.
The following shows sample input and output for two test cases.
Sample Input 1
19
Output for the Sample Input 1
HAPPY
Sample Input 2
5
Output for the Sample Input 2
UNHAPPY
题解
题意
按照题中操作,如果能得到1,就是happy。反之,输出unhappy
思路
简单的思路,按顺序模拟即可。
代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <map>
using namespace std;
int n;
map <int, int> m;
int main()
{
bool flag = true;
scanf("%d", &n);
m.clear();
while (n != 1)
{
if (m[n])
{
flag = false;
break;
}
m[n] = 1;
int temp = 0;
while (n)
{
temp += (n%10)*(n%10);
n /= 10;
}
n = temp;
}
if (flag)
printf("HAPPY\n");
else
printf("UNHAPPY\n");
return 0;
}