问题描述:
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其中的几个,那么就不是ugly number,所以,我们只需要把该整数所有的2,3,5素因子除完,看看最后值是否等于1即可。
过程详见代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class Solution { public: bool isUgly(int num) { int last = num; while(num > 0) { if(num % 2 == 0) num = num / 2; if(num % 3 == 0) num = num / 3; if(num % 5 == 0) num = num / 5; if(last == num) break; last = num; } return num == 1; } };
最后
以上就是搞怪便当最近收集整理的关于Ugly Number问题及解法的全部内容,更多相关Ugly内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复