美文网首页
[刷题防痴呆] 0263 - 丑数 (Ugly Number)

[刷题防痴呆] 0263 - 丑数 (Ugly Number)

作者: 西出玉门东望长安 | 来源:发表于2021-11-03 00:44 被阅读0次

题目地址

https://leetcode.com/problems/ugly-number/description/

题目描述

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

思路

  • 看这个数是否只有2,3,5的因子.
  • 如果n==1, return true.
  • 对于2, 3, 5不停去掉2, 3, 5, 最后看num == 1.

关键点

代码

  • 语言支持:Java
class Solution {
    public boolean isUgly(int n) {
        if (n <= 0) {
            return false;
        }
        if (n == 1) {
            return true;
        }
        while (n >= 2 && n % 2 == 0) {
            n /= 2;
        }
        while (n >= 3 && n % 3 == 0) {
            n /= 3;
        }
        while (n >= 5 && n % 5 == 0) {
            n /= 5;
        }
        return n == 1;
    }
}

相关文章

网友评论

      本文标题:[刷题防痴呆] 0263 - 丑数 (Ugly Number)

      本文链接:https://www.haomeiwen.com/subject/jhlzaltx.html