Algorithm

[C++] 백준 14954번: Happy Number

욜스터 2022. 10. 17. 20:27
728x90

https://www.acmicpc.net/problem/14954

 

14954번: Happy Number

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)

www.acmicpc.net

문제

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.

 

풀이

 

답안코드

#include <iostream>
using namespace std;
#define MAXN ((int)1e3)

int N;
int used[MAXN + 10];

void InputData() {
    cin >> N;
}

int cal(int number) {
    int sol = 0;
    int tmp = number;

    while (number != 0) {
        tmp = (number % 10);
        sol += (tmp * tmp);
        number /= 10;
    }
    return sol;
}

void Solve(int num) {

    while (1)
    {
        num = cal(num);

        if (num == 1) {
            cout << "HAPPY";
            return;
        }

        else if (used[num] == 1) break;

        used[num] = 1;
    }
    cout << "UNHAPPY";
}

int main() {

    InputData();

    Solve(N);

    return 0;
}
728x90
반응형

'Algorithm' 카테고리의 다른 글

[C++] 백준 2670번: 연속부분최대곱  (0) 2022.10.17
[C++] 백준 2578번: 빙고  (0) 2022.10.17
[C++] 백준 2567번: 색종이2  (0) 2022.10.06
[C++] 백준 2477번: 참외밭  (0) 2022.10.06
[백준]9012번: 괄호- 파이썬  (0) 2022.06.14