백준 14954 Happy Number

문제

Consider the following function f defined for any natural number n:

f(n) is the number obtained by summing up the squares of the digits of n in decimal (or base-ten).

If n = 19, for example, then f(19) = 82 because 12 + 92 = 82.

Repeatedly applying this function f, some natural numbers eventually become 1. Such numbers are called happy numbers. For example, 19 is a happy number, because repeatedly applying function f to 19 results in:

  • f(19) = 12 + 92 = 82
  • f(82) = 82 + 22 = 68
  • f(68) = 62 + 82 = 100
  • f(100) = 12 + 02 + 02 = 1

However, not all natural numbers are happy. You could try 5 and you will see that 5 is not a happy number. If n is not a happy number, it has been proved by mathematicians that repeatedly applying function f to n reaches the following cycle:

4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.

Write a program that decides if a given natural number n is a happy number or not.

입력
Your program is to read from standard input. The input consists of a single line that contains an integer, n (1 ≤ n ≤ 1,000,000,000)

출력
Your program is to write to standard output. Print exactly one line. If the given number n is a happy number, print out HAPPY; otherwise, print out UNHAPPY.

예제 입력 1
19

예제 출력 1
HAPPY

예제 입력 2
5

예제 출력 2
UNHAPPY

풀이 과정

f(n)의 값을 넣을 리스트를 선언하고 n을 삽입해둔다.

반복을 하면서 f(n)을 계속 구한다.
구한 값이 1이면 종료하고 HAPPY를 출력한다.
구한 값이 구했던 값의 리스트에 존재하면 종료하고 UNHAPPY를 출력한다.
둘 다 아니면 리스트에 구한 값을 삽입하고, 다음으로 구할 f(n)을 만들고 반복한다.

코드

n = int(input())
digits = list(map(int, str(n)))
values = [n]
result = ''
while True:
    value = 0
    for digit in digits:
        value += digit ** 2
    if value == 1:
        result = 'HAPPY'
        break
    if value in values:
        result = 'UNHAPPY'
        break
    values.append(value)
    digits = list(map(int, str(value)))
print(result)

백준 14954 Happy Number

좋은 웹페이지 즐겨찾기