Ugly number
Title description: Give you an integer n, please judge whether n is an ugly number. If yes, return true; otherwise, return false.
Ugly numbers are positive integers that contain only prime factors 2, 3, and/or 5.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/ugly-number/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: Traverse
- First, if n is equal to 0, return false directly.
- Loop processing removes all prime factors 2, 3, and 5 of n, and then loop processing. If n is
2~Math.sqrt(n)
by any number of 0614c789581432, it returns false; otherwise, if n is any of 1, 2, 3, and 5. A number, return true, otherwise return false.
public class LeetCode_263 {
public static boolean isUgly(int n) {
if (n == 0) {
return false;
}
while (n % 2 == 0) {
n = n / 2;
}
while (n % 3 == 0) {
n = n / 3;
}
while (n % 5 == 0) {
n = n / 5;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
if (n == 1 || n == 2 || n == 3 || n == 5) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
System.out.println(isUgly(920408890));
}
}
[Daily Message] all things, hope is the most beautiful.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。