【LeetCode】263. Ugly Number 丑数(Easy)(JAVA)

【LeetCode】263. Ugly Number 丑数(Easy)(JAVA)

题目地址: https://leetcode.com/problems/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 treated as an ugly number.
  • Input is within the 32-bit signed integer range: [−2^31,  2^31 − 1].

题目大意

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

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

解题方法

  1. 判断是否能整除 2,3,5, 如果能整除,把含有的 2,3,5 全部除尽
  2. 最后如果剩下的是 1 ,就说明是 ugly number
class Solution {
    public boolean isUgly(int num) {
        if (num <= 0) return false;
        int[] primes = new int[]{2, 3, 5};
        for (int i = 0; i < primes.length; i++) {
            while (num % primes[i] == 0) {
                num /= primes[i];
            }
        }
        return num == 1;
    }
}

执行耗时:1 ms,击败了100.00% 的Java用户
内存消耗:35.6 MB,击败了64.25% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新

你可能感兴趣的:(Leetcode,java,leetcode,算法,面试,数据结构)