*Ugly number

來源:互聯網
上載者:User

標籤:

 

 

題目:

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.

題目大意:

編寫程式判斷一個給定的數字是否為“醜陋數” ugly number

醜陋數是指只包含質因子2, 3, 5的正整數。例如,6, 8是醜陋數而14不是,因為它包含額外的質因子7

注意,數字1也被視為醜陋數

解題思路:

將輸入數重複除2, 3, 5,判斷得數是否為1即可

時間複雜度:

記num = 2^a * 3^b * 5^c * t,程式執行次數為 a + b + c,換言之,最壞情況為O(log num)

 

 1 public class Solution { 2     public boolean isUgly(int num)  3     { 4         if(num <= 0) return false; 5         int [] prime = {2,3,5}; 6         for (int x:prime) 7         { 8             while(num%x==0) 9             num/=x;10         }11         12         return num==1;13         14     }15 }

reference: http://bookshadow.com/weblog/2015/08/19/leetcode-ugly-number/

*Ugly number

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.