Algolithm-Leetcode/Math & Geometry
Happy Number
꿀잠마스터
2026. 8. 23. 21:24
https://leetcode.com/problems/happy-number/description/
Happy Number - LeetCode
Can you solve this real interview question? Happy Number - 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 squar
leetcode.com
주어진 조건을 만족하는지 체크하는 문제이다. 단순 수식 구현 문제로 문제에서 제시하는 조건들을 따라 해결해 나가면 된다. 숫자를 10의 자리 단위로 분해하여 제곱 해서 더해야 하므로 %, / 연산자를 써서 해결해 나가면 된다. 최종 조건인 1이 되는 경우 외에도 무한히 반복되는 경우로 4가 있었다. 이를 체크하기 위해 set을 이용하여 사이클 체크를 해주었다.
import java.util.*;
public class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while(n > 1){
int sum = 0;
while(n > 0){
int mod = n % 10;
sum += mod * mod;
n = n / 10;
}
n = sum;
if(set.contains(n)) break;
set.add(n);
}
return n == 1;
}
}