前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T45-丑数

【leetcode刷题】T45-丑数

作者头像
木又AI帮
修改2019-07-18 10:03:48
4600
修改2019-07-18 10:03:48
举报
文章被收录于专栏:木又AI帮木又AI帮

【英文题目】(学习英语的同时,更能理解题意哟~)

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.

Example 1:

代码语言:javascript
复制
Input: 
Output: true
Explanation:  =  × 

Example 2:

代码语言:javascript
复制
Input: 
Output: true
Explanation:  =  ×  × 

Example 3:

代码语言:javascript
复制
Input: 
Output: false 
Explanation:  is not ugly since it includes another prime factor 7.

Note:

  1. 1 is typically treated as an ugly number.
  2. Input is within the 32-bit signed integer range: [−231,  231 − 1].

【中文题目】

编写一个程序判断给定的数是否为丑数。

丑数就是只包含质因数 2, 3, 5正整数

示例 1:

代码语言:javascript
复制
输入: 
输出: true
解释:  =  × 

示例 2:

代码语言:javascript
复制
输入: 
输出: true
解释:  =  ×  × 

示例 3:

代码语言:javascript
复制
输入: 
输出: false 
解释:  不是丑数,因为它包含了另外一个质因数 。

说明:

  1. 1 是丑数。
  2. 输入不会超过 32 位有符号整数的范围: [−231,  231 − 1]。

【思路】

只要num能被2、3、5整除,则除以2、3、5,最后判断num是否为1.

注意num=0时需特殊处理。

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def isUgly(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num == :
            return False
        while num %  == :
            num /=
        while num %  == :
            num /= 
        while num %  == :
            num /= 
        return num == 

C++版本

代码语言:javascript
复制
class Solution {
public:
    bool isUgly(int num) {
        if(num == )
            return false;
        while(num %  == )
            num /= ;
        while(num %  == )
            num /= ;
        while(num %  == )
            num /= ;
        if(num == )
            return true;
        return false;
    }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-04-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档