标签:
题目链接:https://leetcode.com/problems/ugly-number/
题目:
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
. 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.
题目理解:判断一个给定的数是否是丑数。所谓丑数,就是那些因子只含2,3,5的数。1是自小丑数
最直接的代码如下:
public class Solution { public boolean isUgly(int num) { if(num <= 0) return false; if(num == 1) { return true; } while(num % 2 == 0) { num /= 2; } while(num % 3 == 0) { num /= 3; } while(num % 5 == 0) { num /= 5; } return num == 1 ? true : false; } }
结果超时。。。
然后改进了一下,AC。代码如下:
public class Solution { public boolean isUgly(int num) { if(num <= 0) return false; if(num == 1) { return true; } if(num % 5 == 0) { return isUgly(num / 5); } else if(num % 3 == 0) { return isUgly(num / 3); } else if(num % 2 == 0) { return isUgly(num / 2); } else { return false; } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/yangyao_iphone/article/details/47777335