translation
number)。丑数是一个正数,它的质因子只包括2、3、5。例如,6、8是丑数,而因为包含了7这个因子,所以14不是丑数。请注意,1通常被视为一个丑数。
Original
Write a program toCheck whether agiven Number isAn ugly Number. Ugly numbers is positive numberswhosePrime factors only include2,3,5.For example,6,8Is ugly while - is notUglysince itIncludes another prime factor7.Note that 1 isTypically treated asAn ugly Number.
Analysis
In the face of test instructions is not very clear topic, my usual practice is to write a knowledge is wrong to verify the method.
For example, when I first tried, I found 4 is ugly number: 2 x 2 x 1, please note the 1 here, please note that the title of 1 is an ugly number. Then it's natural to have a line like this:
if1returntrue;
There's another way to use the code, and it's going to go on. Because the ugly number is positive, so 0 is not:
if0returnfalse;
Back to the example above, 4, we can let it divide 2 at a time, but then it can be divided by a 2, obviously, this requires recursion. If it is 8, divide it by 3 times, the last factor is 1, and return to true.
And for 14, divided by 2 is 7, but 7 for 2, 3, 5 is not 0, the same, if it is 28, will be divided two times 2, the last of the same result.
OK, back to 0 and 1, the reason they're both so important is because they want to be a recursive termination condition. Obviously, 1 should be returned true,0 return false, but ultimately if not divisible directly is a return false, then can not be combined so that NUM is not judged whether 0? Also cannot, because this will cause a dead loop, 0 divided by any number is still 0.
So the problem was solved.
Code
Class Solution { Public:BOOL isugly(intNUM) {if(num = =0)return false;Else if(num = =1)return true;Else if(num%2==0)returnisugly (num/2);Else if(num%3==0)returnisugly (num/3);Else if(num%5==0)returnisugly (num/5);Else return false; }};
Leetcode 263 Ugly Number