LeetCode笔记:263. 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整除的正数。比如说,6、8是丑数字而14就不是丑数字因为它还有7这个约数。
注意1也被看待成丑数字。

思路:

leetcode中的题目都有有意思,一会happy数字一会ugly数字,也不知道是国外就这么叫的还是纯粹出题人有童心。这个题想着也没什么好办法,只能分别对2、3、5去看能不能被整除,能就除一下继续判断,直到不能被2、3、5整数了为止,看结果是不是1,是的话就是丑数字了,不是则不丑。看了看别人的做法,也大都是这个思路,这是实现上可能有点小差异。
还有一个要注意的是题目说丑数字是个正数,但没说给出的数字都是正数,在这里栽了个跟头,被0和负数弄得错了两次,我的Accepted率啊。。。

代码(Java):

public class Solution {
    public boolean isUgly(int num) {
        if (num <= 0) return false;
        while (true) {
            if (num % 2 == 0) {
                num = num / 2;
            } else if (num % 3 == 0) {
                num = num / 3;
            } else if (num % 5 == 0) {
                num = num / 5;
            } else if (num == 1) {
                return true;
            } else {
                return false;
            }
        }
    }
}

合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值