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:
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.
19
HAPPY
5
UNHAPPY
이 문제에서 유의해야 할 점은 값이 4가 나오면 무조건 UNHAPPY Number가 된다는 점이다.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
String unhap = "4";
do{
str = happy(str);
if(str.equals(unhap)) {
System.out.println("UNHAPPY");
return ;
}
}while(!str.equals("1"));
System.out.println("HAPPY");
}
public static String happy(String origin) {
int k = 0;
for(int i=0; i<origin.length(); i++) {
k += Math.pow(Character.getNumericValue(origin.charAt(i)), 2);
}
return Integer.toString(k);
}
}