leetcode263- Ugly Number- easy

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.

 

1.把2一直除到底,把3一直除到底,把5一直除到底。最后如果到1了就是。

2. 一直找当前能不能有一个整除即可,不能整除直接跳出。最后判断到1没有。

 

实现1:

class Solution {
    public boolean isUgly(int num) {
        for (int i = 2; i <= 5 && num > 0; i++) {
            while (num % i == 0) {
                num /= i;
            }
        }
        return num == 1;
    }
}

 

 

实现2:

class Solution {
    public boolean isUgly(int num) {
        if (num < 1) {
            return false;
        }
        int[] bank = {2, 3, 5};
        boolean hasValidFactor = true;
        
        while (num > 1 && hasValidFactor) {
            hasValidFactor = false;
            for (int i = 0; i < bank.length; i++) {
                if (num % bank[i] == 0) {
                    hasValidFactor = true;
                    num /= bank[i];
                    break;
                }
            }
        }
        
        return num == 1;
    }
}

 

posted @ 2017-12-04 08:24  jasminemzy  阅读(109)  评论(0编辑  收藏  举报