Skip to content

Latest commit

 

History

History
85 lines (60 loc) · 1.93 KB

263-ugly-number.md

File metadata and controls

85 lines (60 loc) · 1.93 KB

263. Ugly Number - 丑数

编写一个程序判断给定的数是否为丑数。

丑数就是只包含质因数 2, 3, 5 的正整数

示例 1:

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

示例 2:

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

示例 3:

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

说明:

  1. 1 是丑数。
  2. 输入不会超过 32 位有符号整数的范围: [−231,  231 − 1]。

题目标签:Math

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
cpp 4 ms 8 MB
int factors[] = {2, 3, 5};

class Solution {
public:
    bool isUgly(int num) {
        if (num <= 0) return false;
        if (num < 2) return true;
        for (int n : factors) {
            if (num % n == 0) {
                return isUgly(num / n);
            }
        }
        return false;
    }
};
Language Runtime Memory
python3 76 ms N/A
class Solution:
    def isUgly(self, num):
        """
        :type num: int
        :rtype: bool
        """
        for pf in (2, 3, 5):
            while num != 0 and not num % pf:
                num //= pf
        return num == 1