?LeetCode刷題實(shí)戰(zhàn)263:丑數(shù)
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return true if n is an ugly number.
示例
示例 1:
輸入:n = 6
輸出:true
解釋?zhuān)?span style="color: rgb(0, 128, 128);background: rgba(0, 0, 0, 0);display: inline;width: 6px;text-decoration: none solid rgb(0, 128, 128);font-weight: 400;font-style: normal;">6 = 2 × 3
示例 2:
輸入:n = 8
輸出:true
解釋?zhuān)?span style="color: rgb(0, 128, 128);background: rgba(0, 0, 0, 0);display: inline;width: 6px;text-decoration: none solid rgb(0, 128, 128);font-weight: 400;font-style: normal;">8 = 2 × 2 × 2
示例 3:
輸入:n = 14
輸出:false
解釋?zhuān)?span style="color: rgb(0, 128, 128);background: rgba(0, 0, 0, 0);display: inline;width: 13px;text-decoration: none solid rgb(0, 128, 128);font-weight: 400;font-style: normal;">14 不是丑數(shù),因?yàn)樗肆硗庖粋€(gè)質(zhì)因數(shù) 7 。
示例 4:
輸入:n = 1
輸出:true
解釋?zhuān)?span style="color: rgb(0, 128, 128);background: rgba(0, 0, 0, 0);display: inline;width: 6px;text-decoration: none solid rgb(0, 128, 128);font-weight: 400;font-style: normal;">1 通常被視為丑數(shù)。
解題
class Solution {
public boolean isUgly(int num) {
if(num <= 0) return false;
while(num % 2 == 0) num /= 2;
while(num % 3 == 0) num /= 3;
while(num % 5 == 0) num /= 5;
return num == 1;
}
}
