[LeetCode] 263. Ugly Number

丑陋数字I,弱智题。题意是判断一个正整数是否为ugly number。ugly number的定义是这个数字只能被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整除即可。代码如下

时间O(n)

空间O(1)

 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 };

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/11713145.html