LeetCode之旅(17)-Ugly Number

时间:2021-12-18 05:30:27

题目:

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,3,5相加组成

代码:

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