leetcode263-- Ugly Number

leetcode263-- 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.

Example 1:

Input: 6
Output: true
Explanation: 6 = 2 × 3
Example 2:

Input: 8
Output: true
Explanation: 8 = 2 × 2 × 2
Example 3:

Input: 14
Output: false 
Explanation: 14 is not ugly since it includes another prime factor 7.
Note:

1 is typically treate as the first ugly number

###


class Solution(object):
    def isUgly(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num ==0:
            return False
        if num == 1:
            return True
        
        pms = [2,3,5]
        
        for x in pms:
            while num%x==0:
                num /= x

        return num==1
    
        

也可以这样

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

即约掉几个更大的数字.

打赏,谢谢~~

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,多谢支持~

打开微信扫一扫,即可进行扫码打赏哦