本文主要是介绍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其中的几个,那么就不是ugly number,所以,我们只需要把该整数所有的2,3,5素因子除完,看看最后值是否等于1即可。
过程详见代码:
class 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问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!