丑数 Ugly Number
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
問(wèn)題:
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.
解決:
① 丑陋數(shù)就是其質(zhì)數(shù)因子只能是2,3,5。那么最直接的辦法就是不停的除以這些質(zhì)數(shù),如果剩余的數(shù)字是1的話就是丑陋數(shù)了,如下所示:
public class Solution {//2ms
? ? public boolean isUgly(int num) {
? ? ? ? while (num >= 2) {
? ? ? ? ? ? if (num % 2 == 0) num /= 2;
? ? ? ? ? ? else if (num % 3 == 0) num /= 3;
? ? ? ? ? ? else if (num % 5 == 0) num /= 5;
? ? ? ? ? ? else return false;
? ? ? ? }
? ? ? ? return num == 1;
? ? }
}
同一個(gè)思路:
public class Solution {//2ms
? ? 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;
? ? }
}
轉(zhuǎn)載于:https://my.oschina.net/liyurong/blog/1143037
總結(jié)
以上是生活随笔為你收集整理的丑数 Ugly Number的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 绿色数据中心建设刻不容缓
- 下一篇: Pandas库学习笔记