KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (486)
    • ALGORITHM (11)
      • 정렬 (6)
      • 최단경로 (1)
      • 자료구조 (1)
      • 슬라이딩 윈도우 (1)
      • etc (2)
    • Git (5)
    • Web (24)
      • Vanilla JS (13)
      • TS (2)
      • React (7)
      • ETC (1)
    • React 공식문서 (번역, 공부) (11)
      • Quick Start (2)
      • Installation (0)
      • Describing the UI (9)
      • Adding Interactivity (0)
      • Managing State (0)
      • Escape Hatches (0)
    • Next.js 공식문서 (번역, 공부) (3)
      • Getting Started (2)
      • Building Your Application (1)
    • PS (431)
      • 백준 (187)
      • Programmers (104)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • codeup
  • programmers
  • 정렬
  • 문자열
  • string
  • C
  • 백준
  • Level1
  • 다이나믹 프로그래밍
  • tree
  • Level 0
  • 수학
  • Level 1
  • 그래프
  • LeetCode
  • recursion
  • js
  • C++
  • Level 2
  • 제코베 JS 100제

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/LeetCode

LeetCode / Implementation / 202번 / Happy Number / JS

2023. 4. 18. 01:50

< 문제 바로가기 >

 

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

 

< 문제 간단설명 >
양의 정수 n이 입력값으로 들어온다. n의 각 자리를 나누어서 각각 제곱을 한 뒤 더해준 것이 다음 수가 된다. 이 과정을 1이 될 때 까지 반복한다. 1이 된다면 true를 반환하고 무한루프에 빠진다면 false를 반환한다.

 

예를 들어 19일 경우, 1^2 + 9^2 = 82가 되고, 다시 8^2 + 2^2 = 68, 6^2 + 8^2 = 100, 1^2 + 0^2 + 0^2 = 1이 된다. 따라서 true를 반환한다.

 

/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function(n) {
    let numSet = new Set();

    let num = n;
    let sum = 0;
    while(true) {
        sum = 0;
        if(num === 1) return true;

        num.toString().split('').map(Number).forEach((el) => {
            sum += el ** 2;
        });
        num = sum;

	// 이미 set에 저장되어 있는수라면 무한루프이므로 false 반환
        if(numSet.has(sum)) {
            return false;
        }
        numSet.add(sum);
    }
};

 

저작자표시 (새창열림)

'PS > LeetCode' 카테고리의 다른 글

LeetCode / String / 14번 / Longest Common Prefix / JS  (0) 2023.04.19
LeetCode / Simulation / 54번 / Spiral Matrix / JS  (0) 2023.04.18
LeetCode / Heap / 692번 / Top K Frequent Words / JS  (0) 2023.04.18
LeetCode / Heap / 1046번 / Last Stone Weight / JS  (0) 2023.04.18
    'PS/LeetCode' 카테고리의 다른 글
    • LeetCode / String / 14번 / Longest Common Prefix / JS
    • LeetCode / Simulation / 54번 / Spiral Matrix / JS
    • LeetCode / Heap / 692번 / Top K Frequent Words / JS
    • LeetCode / Heap / 1046번 / Last Stone Weight / JS
    KimMinJun
    KimMinJun

    티스토리툴바