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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
题意:判断给定的数是否为ugly number。ugly number定义:给定数num的质因子只能包括2、3、5.
例:6的质因子为2和3,因此6是ugly number;8的质因子为2,因此8是ugly number;14的质因子为2和7,因此14不是ugly number
质数(Prime number),又称素数,指在大于1的自然数中,除了1和该数自身外,无法被其他自然数整除的数(也可定义为只有1与该数本身两个正因数的数)。
质因子(或质因数)在数论里是指能整除给定正整数的质数。每个正整数都能够以唯一的方式表示成它的质因数的乘积。
以上内容摘自维基百科。
因此,质因子是针对正数而言的。因此对于负数,就可以直接判断其不是ugly number
public boolean isUgly(int num) { if(num <= 0) return false; if(num == 1) return true; while(num % 2 == 0 || num % 3 == 0 || num % 5 == 0){ if(num % 2 == 0) num /= 2; if(num % 3 == 0) num /= 3; if(num % 5 == 0) num /= 5; if(num == 1) return true; } return false; }