【LeetCode】Ugly Number 解题报告

Ugly Number

[LeetCode]

https://leetcode.com/problems/ugly-number/

Total Accepted: 22335 Total Submissions: 67449 Difficulty: Easy

Question

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.

Examples

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.

Ways

方法一

把这个数中的所有的2,3,5的因子全部除去,剩余的数为1,则说明全部为这几个因子构成

public static boolean isUgly(int num) {
    if (num == 1) {
        return true;
    }

    while (num >= 2 && num % 2 == 0) {
        num = num / 2;
    }
    while (num >= 3 && num % 3 == 0) {
        num = num / 3;
    }
    while (num >= 5 && num % 5 == 0) {
        num = num / 5;
    }
    return num == 1;
}

Solution

托管在我的GitHub上:

https://github.com/fuxuemingzhu/UglyNumber

Captures

测试结果截图:

Reference

http://blog.csdn.net/xudli/article/details/47786867

Date

2015/10/16 21:20:23

你可能感兴趣的:(LeetCode)