우사미 코딩

[LeetCode] 202. Happy Number - 주옥같은 해피넘버 본문

Leetcode

[LeetCode] 202. Happy Number - 주옥같은 해피넘버

맑은 눈의 우사미 2023. 5. 17. 09:46
반응형

1. 문제 링크

 

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

 

 

 

2. n을 한자리수로 쪼개서 제곱한 값을 모두 더한 값이 1이되면 해피넘버

input이 해피넘버이면  true 리턴, 아니면 false리턴

- Input: n = 19

 

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

 

 

 

3. 저딴식으로 더하면 circle이 될 수 있다

leetcode description에서 쌔벼옴

 

input넘버가 4인 경우에도 ㅈ같은 서클이 생성된다

ㅈ같은 서클은 모다? 해피넘버가 아니라는거시다; false를 리턴해야함

 

 

4.  한자릿수로 쪼개서 제곱근을 더한값들을 map에 저장해두쟈

만약 맵에 똑같은 결과값이 있다? 그럼 이것은 해피넘버가 아니기 때무넹 return false해야한다

input값의 최종 결과는 1이거나 circle이다

 

 

5. solution

class Solution {
public:
    bool isHappy(int n) {
        map<int, int> m;
        while(n != 1){
            int num = 0;
            while(n > 0){
                int curr = n % 10;
                num += curr * curr;
                n = n / 10;
            }
            if(num == 1)
                break;

            if(m[num]++ > 1)
                return false;
            n = num;
        }
        return true;
    }
};
반응형
Comments