Write a program to check whether a given number was an ugly number.
Ugly numbers is positive numbers whose prime factors only include2, 3, 5
. For example,6, 8
Is ugly while14
is not ugly since it includes another prime factor7
.
Note that's 1
typically treated as an ugly number.
Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.
AC Code:
Class Solution {public: bool isugly (int num) { if (num==0) return false; while (num!=1) { if (num%2==0) NUM=NUM/2; else if (num%3==0) NUM=NUM/3; else if (num%5==0) NUM=NUM/5; else break ; } return num==1;} ;
write a program to find The n
-th ugly number.
ugly numbers is positive numbers whose prime factors only Include 2, 3, 5
. For Example, 1, 2, 3, 4, 5, 6, 8, 9, ten,
is the sequence of the First 10
ugly numbers.
Note that's 1
typically treated as an ugly number.
Of course it is possible to use the judgment function of I for a number and a number, but the time efficiency is not high.
AC Code:
Class Solution{public: int minnum (int x,int y) { return x<y?x:y; } int nthuglynumber (int n) { if (n==0) return 0; int *count=new Int[n]; Count[0]=1; int two=0; int three=0; int five=0; int sum=1; int min=0; while (Sum<n) { min=minnum (Minnum (count[two]*2,count[three]*3), count[five]*5); if (Min>count[sum-1]) { count[sum]=min; ++sum; } if (min==count[two]*2) ++two; else if (min==count[three]*3) ++three; else ++five; } return count[sum-1];} ;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode 263 264] Ugly number I II