.Zzumbong

[leetCode/JS] 263. Ugly Number 본문

coding test/leetCode

[leetCode/JS] 263. Ugly Number

쭘봉 2022. 11. 23. 11:30

문제 설명

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

Given an integer n, return true if n is an ugly number.

입출력 예

Example 1:

Input: n = 6

Output: true
Explanation: 6 = 2 × 3

Example 2:

Input: n = 1
Output: true
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.

Example 3:

Input: n = 14
Output: false
Explanation: 14 is not ugly since it includes the prime factor 7.

Constraints

  • -231 <= n <= 231 - 1

내 솔루션

  • 뭐.. 2, 3, 5 로 나눠질떄까지 나누다가 n이 1이되어 while을 빠져나오면 true,
  • 아니면 false인 상황이다.
var isUgly = function(n) {
  if(n <= 0) return false;
  while(n !== 1){
    if(n % 2 === 0){
      n /= 2;
    } else if(n % 3 === 0){
      n /= 3;
    } else if(n % 5 === 0){
      n /= 5;
    } else {
      return false;
    }
  }
  return true;
};

감상평

  • 왜 2, 3, 5로 나눠지는 이 숫자가 어글리 할까? 몰?루
Comments