Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include
2, 3, 5
. For example,6, 8
are ugly while14
is not ugly since it includes another prime factor7
.Note that
1
is typically treated as an ugly number.
【解题思路】:
将num除以2,将整除结果赋值给num,直到无法被2整除,3、5也同理。最后如果得到结果为1,则返回true,否则返回false。
【代码实现】:
public class Solution { public boolean isUgly(int num) { if(num == 0) return false; //之前忘了num=0的情况,超时了 while(num % 2 == 0) num /= 2; while(num % 3 == 0) num /= 3; while(num % 5 == 0) num /= 5; if(num == 1) return true; return false; } }
1012 / 1012 test cases passed. Runtime: 2 ms
最后,欢迎各位批评指正!