[Swift]LeetCode263. 丑数 | Ugly Number

[Swift]LeetCode263. 丑数 | Ugly Number,第1张

概述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. Example 1: Input: 6Output: trueExplanation: 6 = 2 × 3

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.

Example 1:

input: 6Output: trueExplanation: 6 = 2 × 3

Example 2:

input: 8Output: trueExplanation: 8 = 2 × 2 × 2

Example 3:

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

Note:

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

编写一个程序判断给定的数是否为丑数。

丑数就是只包含质因数 2,5 的正整数。

示例 1:

输入: 6输出: true解释: 6 = 2 × 3

示例 2:

输入: 8输出: true解释: 8 = 2 × 2 × 2

示例 3:

输入: 14输出: false 解释:  不是丑数,因为它包含了另外一个质因数 。147

说明:

1 是丑数。 输入不会超过 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 /= 312         }13         while (number % 5 == 0)14         {15             number /= 516         }17         return number == 118     }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 false11         }12         var no = num13         maxdiv(&no,2)14         maxdiv(&no,3)15         maxdiv(&no,5)16         17         if(no == 1){18             return true19         }20         else {21             return false22         }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 /= d10             }11         }12         return n == 113     }14 }
总结

以上是内存溢出为你收集整理的[Swift]LeetCode263. 丑数 | Ugly Number全部内容,希望文章能够帮你解决[Swift]LeetCode263. 丑数 | Ugly Number所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1023460.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存