[Algorithm] Leetcode_ 202. Happy Number

JAsmine_log·2024년 9월 6일
0

202. 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 squares of its digits.
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.
Return true if n is a happy number, and false if not.

Example 1:

Input: n = 19
Output: true
Explanation:
12+92=821^2 + 9^2 = 82
82+22=688^2 + 2^2 = 68
62+82=1006^2 + 8^2 = 100
12+02+02=11^2 + 0^2 + 0^2 = 1

Example 2:

Input: n = 2
Output: false

  • Constraints:

    1 <= n <= 2^31 - 1

Solution

  • loops endlessly in a cycle which does not include 1.
  • cycle 여부를 확인하는 것이 중요할 것 같아 보임
  • 숫자를 map에 해싱한 후, memory 접근하는 것이 제곱(연산)하는 것보다 느릴 수 있음
  • cycle이 있는지 확인하는 것이 가장 좋음 - map이나 set에 쌓아놓고, 지나간 것중에 하나라도 다시 나오면 cycle 존재

Code

C++


class Solution
{

private:
    bool checkOverp(int result)
    {
        if (cycle.find(result) != cycle.end()) // 값이 있다 
        {
            return false;
        }
        else
        {
            cycle.insert(result); // 값이 없다
            return true;
        }
    }

public:
    set<int> cycle;

    bool isHappy(int n)
    {
        // 123 ? 12...3 => 1...2 => 0..1 =>
        long long result = 0;
        long long mod = 0;

        while (n > 0)
        {
            mod = n%10;
            n /= 10;
            result += mod * mod;
        }

        if (result == 1)
        {
            return true;
        }
        else
        {
            if(!checkOverp(result)){// 값이 있다
                return false;
            }
            else{
                return isHappy(result); // 값이 없다
            }
        }
    }
};
profile
Everyday Research & Development

0개의 댓글