Write an algorithm to determine if a number n is "happy".
A happy number is a number defined by the following process:
Starting with any positive integer,
replace the number by the sum of the squares of its digits,
and repeat the process until the number equals 1 (where it will stay),
or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy numbers.
Return True if n is a happy number, and False if not.
n이 happy number인지 확인하는 알고리즘을 작성하여라.
happy number는 다음에 의해 정의되는 숫자다.
임의의 양의 정수로 시작하여, 숫자를 각 자릿 수의 제곱 합으로 변경하고,
숫자가 1과 같거나 1을 포함하지 않는 무한 싸이클이 될 때까지 과정을 반복한다.
이 과정으로 숫자가 1로 끝날 경우, n은 happy number이다.
n이 happy number일 경우 true를, 그렇지 않으면 false를 반환하라.
풀이 방법
1. 중복되지 않는 정수를 담을 Set 타입의 변수를 선언한다.
2. 반복문을 수행하며, n의 값을 Set에 add하고, 각 자릿 수 별 제곱 합을 구한다.
3. 이 과정을 반복적으로 수행하며, n이 1이 될 경우, 반복문을 중단한다. (happy number)
4. 또는, 이미 이전에 제곱합 처리가 되어 n이 Set에 존재할 경우, 반복문을 중단한다. (infinite cycle)
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while(!set.contains(n)) {
set.add(n);
int temp = n;
n = 0;
while(temp != 0) {
n += (temp % 10) * (temp % 10);
temp /= 10;
}
if(n == 1)
return true;
}
return false;
}
}
'알고리즘 > LeetCode' 카테고리의 다른 글
[JAVA] LeetCode 101 - Symmetric Tree (0) | 2020.12.02 |
---|---|
[JAVA] LeetCode 70 - Climbing Stairs (0) | 2020.12.02 |
[JAVA] LeetCode 121 - Best Time to Buy and Sell Stock (0) | 2020.12.02 |
[JAVA] LeetCode 191 - Number of 1 Bits (0) | 2020.12.02 |
[JAVA] LeetCode 350 - Intersection of Two Arrays II (0) | 2020.12.01 |