题目链接:https://leetcode.com/problems/ugly-number/
Runtime:8ms
1、问题
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.
2、分析
很显然,num<=0 的所有情况都应该返回false,因为因子中有负数,不单单包含2, 3, 5。其次做因子判断,如果数字不能被2、3、5整除,那么返回false,否则返回true啦。
3、小结
没有进行分析就直接写代码是不对滴:
1、没考虑负数
2、while条件不正确:1 < num
3、精简代码:不用对1单独判断
4、实现
class Solution {
public:
bool isUgly(int num) {
if(0 >= num)
return false;
while(1 < num)
{
if(0 == num % 2)
num = num / 2;
else if(0 == num % 3)
num = num / 3;
else if(0 == num % 5)
num = num / 5;
else
return false;
}
return true;
}
};
5、反思
思考后下笔,良策!