题目如下:
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: Input: 14 Output: false Explanation: 14 is not ugly since it includes another prime factor 7. Note: 1.1 is typically treated as an ugly number. 2.Input is within the 32-bit signed integer range: [−231, 231 − 1].
263. Ugly Number
定义仅由任意个2,3,5相乘得到的正整数为ugly数,例如12=223是ugly数,45=335是ugly数,1是特殊的ugly数。输入一个正整数,让我们判断它是不是ugly数。
解决这道题,只需不断用2,3,5整除给定的正整数num到不能整除为止,看最后的结果是不是1即可。
实现代码如下:
class Solution { public boolean isUgly(int num) { if (num < 0) { return false; } while (num > 1 && num % 2.0 == 0) { num /= 2; } while (num > 1 && num % 3.0 == 0) { num /= 3; } while (num > 1 && num % 5.0 == 0) { num /= 5; } return num == 1; } }
- 本文固定链接: https://weiguangli.com/archives/478
- 转载请注明: lwg0452 于 Weiguang的博客 发表
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!
Pingback 引用通告: [LeetCode每日一题]264. Ugly Number II | 闪技博客