leetcode 263. Ugly Number(丑数)

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.

丑数:必须是正数,因子分解的话只有2,3,5.
1也是丑数。
判断数字n 是不是丑数。

思路:

首先丑数必须得是正数,负数直接返回false.

然后就对2,3,5一直分解好了,直到不能再分解。
最后剩下的必须得是1(因为其他的就可以进一步分解为1x它自己,就不只2,3,5这3个因子)。

public boolean isUgly(int n) {
    if(n <= 0) return false;
    
    while(n % 2 == 0) n /= 2;
    while(n % 3 == 0) n /= 3;
    while(n % 5 == 0) n /= 5;
    
    if(n == 1) return true;
    return false;
}

你可能感兴趣的:(leetcode,leetcode,算法)