[LeetCode] 263. Ugly Number

Ugly numerals I, mentally title. The question is intended to determine whether it is a positive integer ugly number. Defined ugly number is this number can only be obtained three product 2,3,5. For example,

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.

Accordance with the idea to do it, it can determine whether the 2,3,5 divisible. code show as below

Time O (n)

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

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/11713145.html