본문 바로가기
알고리즘/문제 풀이

[Leetcode] 202. HappyNumber🙃

by 위대한초밥V 2023. 11. 12.

https://leetcode.com/problems/happy-number/

 

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

설명

이 문제를 처음 풀 때는 한자릿수가 되었을 때 1이 아니라면 false가 return되도록 하였다.

그러다보니, 순환이 되는 경우(= 같은 수가 반복해서 나오는 경우)에, HappyNumber가 아님을 고려하지 못했다. 

 

만약 n이 7이라면?

n = 7 👉 7*7 = 49 👉 4*4 + 9*9 = 97 👉 9*9 + 7*7 = 130 👉 1*1 + 3*3 = 10 👉 1*1 + 0*0 = 1 이 된다.

 

그렇다면 이 문제의 종료 조건은 다음과 같이 잡으면 된다.

  • 반복해서 연산을 하다가 1이 되는 경우
  • 순환이 발생하는 경우

순환이 발생하는 경우는 set 자료형을 사용해서

  1. 연산 과정에서 나오는 값들을 저장하고
  2. 만약 연산하다가 포함되어 있으면, 순환이 되는 상황이므로! 🌟false 반환🌟하도록 하면 된다.

코드

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;
    }
}
반응형