Computer Science/Algorithm Problem

백준] 14954 - Happy Number

TwinParadox 2018. 5. 21. 23:16
728x90

시간 제한 : 0.2초

메모리 제한 : 512MB




입력

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>
#include <set>
using namespace std;
int main(void)
{
	int n, m;
	set<int> s;
	cin >> n;
	if (n == 1)
	{
		cout << "HAPPY";
		return 0;
	}
	while (1)
	{
		s.insert(n);
		m = 0;
		while (n >= 10)
		{
			int t = n % 10;
			n /= 10;
			m += t * t;
		}
		m += n * n;
		n = m;
		if (n == 1)
		{
			cout << "HAPPY";
			return 0;
		}
		else if (s.size() > 1 && s.find(n) != s.end())
		{
			cout << "UNHAPPY";
			return 0;
		}
	}
}




Tip

숫자를 자릿수 단위로 쪼개는 과정과 set 활용 방법만 잘 알고 있으면 풀 수 있는 문제다.



728x90
728x90