[Swift]LeetCode263. 丑数 | Ugly Number
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9751111.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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: 6 Output: true Explanation: 6 = 2 × 3
Example 2:
Input: 8 Output: true Explanation: 8 = 2 × 2 × 2
Example 3:
14
7
Note:
1
is typically treated as an ugly number.- Input is within the 32-bit signed integer range: [−231, 231 − 1].
编写一个程序判断给定的数是否为丑数。
丑数就是只包含质因数 2, 3, 5
的正整数。
示例 1:
输入: 6 输出: true 解释: 6 = 2 × 3
示例 2:
输入: 8 输出: true 解释: 8 = 2 × 2 × 2
示例 3:
14
7
说明:
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 /= 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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了