leecode 解题总结:263. Ugly Number

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
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的。1也是丑数。判定一个 给定的数
是否是丑数。最简单的方法:先将该数除以2,直到不能除以2后,如果最后
变成1,说明该数是丑数
再不断除以3,如果变成1,说明是丑数;否则再不断除以5,如果变成1说明
是丑数,如果最后除不尽5,那么就不是质数。
丑数是正整数,因此<=0,不是丑数

输入:
0
1
2 
3 
5

6
14
900
901
输出:
false
true
true
true
true

true
false
true
false

关键:
1 不断累除2,3,5中间不断累除某个数的过程中,只要变成1,说明就是丑数;否则累除完
3个数还不为1,就不是丑数
*/

class Solution {
public:
    bool isUgly(int num) {
		if(num <= 0)
		{
			return false;
		}
		int primeArr[3] = {2,3,5};
		int i = 0;
		while(num != 1)
		{
			//如果数字大于质数,并且对质数取余没有余数(可以除尽),继续做。这里等于也要处理
			while(num >= primeArr[i] && (0 == num % primeArr[i]) )
			{
				while(1 == num)
				{
					return true;
				}
				num /= primeArr[i];
			}
			//判断是否可以处理下一个质数,如果下标超过2,但是当前数字不为1,
			//说明不是丑数
			if(i >= 2)
			{
				if(1 != num)
				{
					return false;
				}
				else
				{
					return true;
				}
			}
			else
			{
				i++;
			}
		}
		return true;
    }
};

void print(vector<int>& result)
{
	if(result.empty())
	{
		cout << "no result" << endl;
		return;
	}
	int size = result.size();
	for(int i = 0 ; i < size ; i++)
	{
		cout << result.at(i) << " " ;
	}
	cout << endl;
}

void process()
{
	 int num;
	 Solution solution;
	 while(cin >> num )
	 {
		 bool result = solution.isUgly(num);
		 if(result)
		 {
			 cout << "true" << endl;
		 }
		 else
		 {
			 cout << "false" << endl;
		 }
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值