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
. 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.
题目标签:Math
题目让我们判断一个数字 是否 是ugly number。
首先 ugly numbers 是正数;1 算做ugly number;然后 ugly numbers 的 prime factors 只能是2, 3, 5;
所以在排除 0 和 负数,还有 1的情况下,只要 用 num 依次 重复除以 2, 3, 5。 如果最后 是1就代表 是 ugly number。
Java Solution:
Runtime beats 23.44%
完成日期:06/16/2017
关键词:math
关键点:依次 重复除以2, 3, 5
1 class Solution 2 { 3 public boolean isUgly(int num) 4 { 5 if(num <= 0) 6 return false; 7 else if(num == 1) 8 return true; 9 10 int[] upf = {2, 3, 5}; 11 12 for(int i=0; i<upf.length; i++) 13 { 14 while(num % upf[i] == 0) // can be divided by upf element 15 { 16 num = num / upf[i]; 17 } 18 } 19 20 return num == 1 ? true : false; 21 } 22 }
参考资料:n/a
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/