[LeetCode] 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.

Note:

  1. 1 is typically treated as an ugly number.
  2. Input is within the 32-bit signed integer range: [−231,  231 − 1].

丑数I。题意是判断一个正整数是否为ugly number。ugly number的定义是这个数字只能被2,3,5三者的乘积所得到。

就按照思路做即可,判断能否被2,3,5整除即可。代码如下

时间O(n)

空间O(1)

JavaScript实现

 1 /**
 2  * @param {number} num
 3  * @return {boolean}
 4  */
 5 var isUgly = function(num) {
 6     if (num === 1) return true;
 7     if (num === 0) return false;
 8     while (num % 2 === 0) num = Math.floor(num / 2);
 9     while (num % 3 === 0) num = Math.floor(num / 3);
10     while (num % 5 === 0) num = Math.floor(num / 5);
11     return num === 1;
12 };

 

Java实现

 1 class Solution {
 2     public boolean isUgly(int num) {
 3         if (num == 1) return true;
 4         if (num == 0) return false;
 5         while (num % 2 == 0) num /= 2;
 6         while (num % 3 == 0) num /= 3;
 7         while (num % 5 == 0) num /= 5;
 8         return num == 1;
 9     }
10 }

 

LeetCode 题目总结

posted @ 2019-10-21 13:47  CNoodle  阅读(127)  评论(0编辑  收藏  举报