[Easy] 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.

 

n의 각 자릿수를 제곱하여 더하고, 이런 과정을 1이 될 때까지 반복한다.

1이 된다면 true, 1이 될 수 없다면 false를 반환한다.

 

예시

Example 1:

Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Example 2:

Input: n = 2
Output: false

 

제약 조건

Constraints:

  • 1 <= n <= 231 - 1
 

해결 과정

재귀를 사용해보았다.

이제 재귀 함수를 혼자의 힘으로 다루는 데에 익숙해진 것 같다.

딱 하나의 TC에 걸려서 문제를 해결하지 못했는데, 그 TC 가 왜 안되는지 이해가 가지 않는다... 😂

내일 스터디원분들과 함께 상의해보아야겠다.

 

  • 재귀 함수 happy를 선언한다.
    • n의 자릿수를 arr 배열에 넣는다.
    • arr배열 요소들을 제곱하여 add 변수에 할당한다.
    • 만약 add의 값이 1이라면 true를 반환한다.
    • add의 값이 1이 아니면서 10보다 작으면 false를 반환한다.

 

해결 코드

/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function(n) {
    
    const happy = (num) => {
        let arr = [];
        
        while(num > 0){
            let temp = num % 10;
            arr.push(temp);
            num = parseInt(num / 10);
        }     
        
        let add = 0;
        arr.forEach((el) => add += el * el);
        
        // 재귀가 끝나는 조건
        if(add === 1) return true;
        else if(add < 10) return false;
        
        return happy(add);
    }
    
    return happy(n);
};

 

 

1111111이 들어오면 각 자릿수의 제곱은 7이니까 false가 맞지 않나..? 라는 생각이다.

왜 true가 나오는지 이해가 가지 않는다.