题目描述
Given an integer n, return true if n is an ugly number.
Ugly number is a positive number whose prime factors only include 2, 3, and/or 5.
样例描述
Example 1:
Input: n = 6
Output: true
Explanation: 6 = 2 × 3
Example 2:
Input: n = 8
Output: true
Explanation: 8 = 2 × 2 × 2
Example 3:
Input: n = 14
Output: false
Explanation: 14 is not ugly since it includes another prime factor 7.
Example 4:
Input: n = 1
Output: true
Explanation: 1 is typically treated as an ugly number.
思路
- 数学问题,只能有这三个质因数,如果不断被这三个数整除,最终结果肯定是1,否则就不是丑数
- 考虑到某个质因数可能有多个,所以在遍历整除时,要用
while
一次把某个质因数全部除干净
代码
class Solution {
public boolean isUgly(int n) {
if (n <= 0) {
return false; //0或者负整数肯定不是丑数
}
int primes[] = {2, 3, 5};
for (int prime: primes){
//这里必须用while不能if 因为可能被同一个多次整除 要一次性除干净
while (n % prime == 0){
n /= prime;
}
}
//若最后因子是1 说明是丑数 否则不是
return n == 1;
}
}