Leetcode P0263"Ugly Number" 题解

2021/05/24 Leetcode

博文中会简要介绍Leetcode P0263题目分析及解题思路。

“Ugly Number”是一道十分简单的题目,依据题目要求对给定的三个素数因子进行整除即可,最终若结果不为1,则说明不是Ugly Number

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

Given an integer n, return true if n is an ugly number.

以下是Java的题解代码实现。

class Solution {
    public boolean isUgly(int num) {
        if (num == 0)
            return false;
        
        int[] primes = new int[] {2, 3, 5};
        for (int p: primes) {
            while (num%p == 0) {
                num /= p;
            }
        }
        
        return (num == 1);
    }
}

以下是C++的题解代码实现。

class Solution {
public:
    bool isUgly(int n) {
        if (n == 0)
            return false;
        
        int primes[3] = {2, 3, 5};
        for (int p: primes) {
            while (n%p == 0) {
                n /= p;
            }
        }
        
        return (n == 1);
    }
};

Search

    Table of Contents