LeetCode每日一题: 丑数(No.263)

栏目: 编程工具 · 发布时间: 6年前

编写一个程序判断给定的数是否为丑数。
丑数就是只包含质因数 2, 3, 5 的正整数。
复制代码

示例:

输入: 6
输出: true
解释: 6 = 2 × 3

输入: 8
输出: true
解释: 8 = 2 × 2 × 2

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

思考:

因为丑数只能包含质因数2,3,5。
所以判断一个数是否为丑数只要将这个数不断与2,3,5相除,只要除的尽,并且最终结果为1,即为丑数。
复制代码

实现:

class Solution {
public boolean 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;
    }
    return num == 1;
}
}复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Data Structures and Algorithms in Java

Data Structures and Algorithms in Java

Michael T. Goodrich、Roberto Tamassia / Wiley / 2010-01-26 / USD 177.41

* This newest edition examines fundamental data structures by following a consistent object-oriented framework that builds intuition and analysis skills of data structures and algorithms * Presents ne......一起来看看 《Data Structures and Algorithms in Java》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试