[LeetCode][JavaScript]Ugly Number
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
. For example, 6, 8
are ugly while 14
is not ugly since it includes another prime factor 7
.
Note that 1
is typically treated as an ugly number.
https://leetcode.com/problems/ugly-number/
质因数只能包含2,3和5。
直接去除2,3和5,除到剩1为止。
1 /** 2 * @param {number} num 3 * @return {boolean} 4 */ 5 var isUgly = function(num) { 6 if(num <= 0){ 7 return false; 8 } 9 while(num !== 1){ 10 if(num % 2 === 0){ 11 num /= 2; 12 continue; 13 } 14 if(num % 3 === 0){ 15 num /= 3; 16 continue; 17 } 18 if(num % 5 === 0){ 19 num /= 5; 20 continue; 21 } 22 return false; 23 } 24 return true; 25 };