Problem:
Write a program to check whether a given number was an ugly number.
Ugly numbers is positive numbers whose prime factors only include 2, 3, 5
. For example, was ugly while was not 6, 8
14
ugly since it includes another prime factor 7
.
Note that's 1
typically treated as an ugly number.
Summary:
Determine if a number is ugly number, which is only 2, 3, 5 of the mass factor.
Analysis:
The method of judging is to divide continuously by 2, 3, 5, see whether the final can get 1. The following two methods are similar.
1 classSolution {2 Public:3 BOOLisugly (intnum) {4 if(Num <=0)return false;5 6 while(num! =1) {7 if(num%2==0) Num/=2;8 Else if(num%3==0) Num/=3;9 Else if(num%5==0) Num/=5;Ten Else return false; One } A - return true; - } the};
1 classSolution {2 Public:3 BOOLisugly (intnum) {4 if(Num <=0)return false;5 6 while(Num >=2&& num%2==0) Num/=2;7 while(Num >=3&& num%3==0) Num/=3;8 while(Num >=5&& num%5==0) Num/=5;9 Ten returnnum = =1; One } A};
Leetcode 263 Ugly Number