给你一个整数 n ,请你判断 n 是否为 丑数 。如果是,返回 true ;否则,返回 false 。
丑数 就是只包含质因数 2、3 和/或 5 的正整数。
示例 1:
输入:n = 6
输出:true
解释:6 = 2 × 3
示例 2:
输入:n = 8
输出:true
解释:8 = 2 × 2 × 2
示例 3:
输入:n = 14
输出:false
解释:14 不是丑数,因为它包含了另外一个质因数 7 。
示例 4:
输入:n = 1
输出:true
解释:1 通常被视为丑数。
来源:力扣(LeetCode)
链接:力扣
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
| public static boolean isUgly(int n) { if (n <= 0) { return false; } int[] factors = {2, 3, 5}; for (int factor : factors) { while (n % factor == 0) { n /= factor; } } return n == 1; }
public static boolean isUglyIteration(int n) { int n2 = n; while (n2 >= 2 && n2 % 2 == 0) { n2 = n2 / 2; } int n3 = n2; while (n3 >= 3 && n3 % 3 == 0) { n3 = n3 / 3; } int n5 = n3; while (n5 >= 5 && n5 % 5 == 0) { n5 = n5 / 5; } return n5 == 1; }
public static boolean isUglyRecursive(int n) { int n2 = n; if (n2 >= 2 && n2 % 2 == 0) { n2 = n2 / 2; return isUglyRecursive(n2); } int n3 = n2; if (n2 >= 3 && n3 % 3 == 0) { n3 = n3 / 3; return isUglyRecursive(n3); } int n5 = n3; if (n2 >= 5 && n5 % 5 == 0) { n5 = n5 / 5; return isUglyRecursive(n5); } return n5 == 1; } |



