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 while 14
is not ugly since it includes another prime factor 7
.
Note that 1
is typically treated as an ugly number.
第一回写的solution,想得太多,代码冗杂,运行时间也偏长:
public class Solution {
public boolean isUgly(int num) {
if(num==1){
return true;
}
if(num==0){
return false;
}
while((num&1)==0){
num/=2;
}
if(num==1){
return true;
}
String sum_bit=Integer.toString(num);
int sum=0;
for(int i=0;i<sum_bit.length();++i){
sum=sum+sum_bit.charAt(i)-48;
}
while((sum%3)==0){
num/=3;
sum_bit=Integer.toString(num);
sum=0;
for(int i=0;i<sum_bit.length();++i){
sum=sum+sum_bit.charAt(i)-48;
}
}
if(num==1){
return true;
}
sum_bit=Integer.toString(num);
char c=sum_bit.charAt(sum_bit.length()-1);
while(c=='5'){
num/=5;
sum_bit=Integer.toString(num);
c=sum_bit.charAt(sum_bit.length()-1);
}
if(num==1){
return true;
}
else{
return false;
}
}
}
再一回,想简单点:
public class Solution {
public boolean isUgly(int num) {
if(num==0)
return false;
while(num%2==0)
num/=2;
while(num%5==0)
num/=5;
while(num%3==0)
num/=3;
return num==1;
}
}
在Discuss中看到的更简洁的Solution:
public class Solution {
public boolean isUgly(int num) {
for(int i=2;i<6&&num>0;++i)
while(num%i==0)
num/=i;
return num==1;
}
}