263. Ugly Number

Easy (Dễ) Python TypeScript 🔗 Xem trên LeetCode

📋 Đề Bài

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

💻 Lời Giải

Python 0263-ugly-number.py
class Solution:
    def isPrime(self, n):
        if n < 2:
            return False
        for i in range(2, int(sqrt(n)) + 1):
            if n % i == 0:
                return False
        return True
    
    def isUgly(self, n: int) -> bool:
        checkPrime = [2, 3, 5]
        
        for pr in checkPrime:
            if n % pr == 0:
                while n >= 1 and n % pr == 0:
                    n /= pr
                    
            if n > 5 and self.isPrime(n):
                return False
            
            if n == 1:
                return True
            
        return False
TypeScript 0263-ugly-number.ts
function isUgly(n: number): boolean {
    if (n <= 0) {
        return false;
    }
    for (let ele of [2, 3, 5]) {
        while (n % ele == 0) {
            n /= ele
        }
    }
    return n == 1
};