[Swift]LeetCode263. 醜數 | Ugly Number

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-uxqcifix-ma.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Write a program to check whether a given number is an ugly number.git

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.github

Example 1:微信

Input: 6
Output: true
Explanation: 6 = 2 × 3

Example 2:spa

Input: 8
Output: true
Explanation: 8 = 2 × 2 × 2

Example 3:code

Input: 14
Output: false 
Explanation:  is not ugly since it includes another prime factor .
147

Note:htm

  1. 1 is typically treated as an ugly number.
  2. Input is within the 32-bit signed integer range: [−231,  231 − 1].

編寫一個程序判斷給定的數是否爲醜數。blog

醜數就是隻包含質因數 2, 3, 5 的正整數。get

示例 1:博客

輸入: 6
輸出: true
解釋: 6 = 2 × 3

示例 2:

輸入: 8
輸出: true
解釋: 8 = 2 × 2 × 2

示例 3:

輸入: 14
輸出: false 
解釋:  不是醜數,由於它包含了另一個質因數 。147

說明:

  1. 1 是醜數。
  2. 輸入不會超過 32 位有符號整數的範圍: [−231,  231 − 1]。

 

20ms

 1 class Solution {
 2     func isUgly(_ num: Int) -> Bool {
 3         if num < 1 {return false}
 4         var number:Int = num
 5         while (number % 2 == 0)
 6         {
 7             number /= 2
 8         }
 9         while (number % 3 == 0)
10         {
11             number /= 3
12         }
13         while (number % 5 == 0)
14         {
15             number /= 5
16         }
17         return number == 1
18     }
19 }

16ms

 1 class Solution {
 2     func maxDiv(_ num: inout Int, _ div: Int) {
 3         while (num % div == 0) {
 4             num = num/div
 5         }
 6     }
 7     
 8     func isUgly(_ num: Int) -> Bool {
 9         if(num == 0) {
10             return false
11         }
12         var no = num
13         maxDiv(&no, 2)
14         maxDiv(&no, 3)
15         maxDiv(&no, 5)
16         
17         if(no == 1){
18             return true
19         }
20         else {
21             return false
22         }
23         
24     }
25 }

20ms

 1 class Solution {
 2     func isUgly(_ num: Int) -> Bool {
 3         guard num > 0 else {return false}
 4         var n = num
 5         
 6         let divs = [2, 3, 5]
 7         for d in divs {
 8             while n % d == 0 {
 9                 n /= d
10             }
11         }
12         return n == 1
13     }
14 }
相關文章
相關標籤/搜索