您的位置:首页 > 编程语言 > C语言/C++

[C++]Ugly Number 丑数

2015-08-19 12:33 579 查看
leetcode 原题链接:https://leetcode.com/problems/ugly-number/

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,3,5. 例如,6,8是丑数 (因为6 = 2*3, 8=2*2*2),而14不是丑数(14=2*7)因为其素数因子包含7.
注意:1是一个特例,也将其看做一个素数。

简要分析:根据其定义可以知道,是丑数一定是正整数,因此从1开始考虑;因此我们可以将需要判断的数进行连除2,3,5;然后判断最后剩下的数,若为1,则是丑数,若不为1不是

实现代码:

#include <iostream>

using namespace std;

class Solution
{
public:
bool isUgly(int num)
{
if (num < 1)
return false;
while (num%2 == 0)
{
num /= 2;
}
while (num % 3 == 0)
{
num /= 3;
}
while (num % 5 == 0)
{
num /= 5;
}
if (num == 1)
return true;
else
return false;
}
};

int main()
{
Solution st;
cout << st.isUgly(14) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息