0263 - Ugly Number
Problem Link
https://leetcode.com/problems/ugly-number/
Problem Statement
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:
Approach 1: Brute Force
Remove all power of from by dividing it by until is no longer divisible by . Repeat the same for and . If becomes then it doesn't have any prime factor other than these three, thus it is an ugly number. Otherwise is not an ugly number.
class Solution {
public:
bool isUgly(int n) {
// Since ugly numbers are positive
if (n <= 0) return false;
array<int, 3> nums {2, 3, 5};
for (int num : nums) {
while (n % num == 0) n /= num;
}
return n == 1;
}
};
- Time Complexity: .
- Space Complexity: .