LeetCode #263 Ugly Number 醜的號碼

英文原文如下

An ugly number is a positive integer whose prime factors are limited to 23, and 5.

Given an integer n, return true if n is an ugly number.

中文翻譯

一個醜的號碼是一個正整數其質因數只限於  23, 跟 5

給予一個整數 n,要是其為醜的號碼則回傳 true 

範例及題目限制


解題思路

醜的號碼定義是正整數,故小於等於 0 的可以直接回傳false 了。

再來,我們可以用個簡單的 while 迴圈來判斷是否可以被 2,3或是5整除

要是最後剩1那就代表是個醜的號碼了~

C# 解決方案

方案1

public class Solution {
    public bool IsUgly(int n) {
        if(n<=0){
            return false;
        }
        while(true){
            if(n%2==0){
                n/=2;
            }
            else if(n%3==0){
                n/=3;
            }
            else if(n%5==0){
                n/=5;
            }
            else if(n==1){
                return true;
            }
            else{
                return false;
            }
        }
    }
}

Java 解決方案

方案1

class Solution {
    public boolean isUgly(int n) {
        if(n<=0){
            return false;
        }
        while(true){
            if(n%2==0){
                n/=2;
            }
            else if(n%3==0){
                n/=3;
            }
            else if(n%5==0){
                n/=5;
            }
            else if(n==1){
                return true;
            }
            else{
                return false;
            }
        }
    }
}

結論

不可以以貌取人~ 數字的話就可以的吧…

🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸

🧡收藏文章或幫我點個廣告,那都是對我的支持

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Ugly Number – LeetCode

一些隨機的LeetCode文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *