LeetCode263 Ugly Number

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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.

样例

1
2
3
4
Input:
10
Output:
true

思路

判断一个数的质因数是否只有2、3、5。

模拟一遍,不断用2、3、5去整除num,看能否能被除尽。

注意特判非正数的情况。

代码

1
2
3
4
5
6
7
8
9
class Solution {
public:
bool isUgly(int num) {
if (num <= 0) return false;
int factor[3] = {2, 3, 5};
for (auto& x: factor) while (num % x == 0) num /= x;
return num == 1;
}
};
分享到 评论