题目:计算第n个丑数的值,如输入9,输出10。丑数:只包含2或3或5为因数的数是丑数。如8=2x2x2,6=2x3,12=2x2x3,所以8,6,12都是丑数;14=2x7,所以14不是丑数。
超时解法(由于不规范使用递归导致超时。。):
public class Solution {
/*
* @param n: An integer
* @return: the nth prime number as description.
*/
public int nthUglyNumber(int n) {
// write your code here
int i = 0;
int nCount = 1; // 从1-n计数
while (nCount <= n) {
i++;
if (isUglyNumber(i)) {
// 如果i是丑数,计数值+1
nCount++;
}
}
return i;
}
/**
* 判断一个数是否是丑数
*/
public boolean isUglyNumber(int n) {
if (n == 1) {
// 递归退出条件,n=1
return true;
} else if (n % 2 == 0) {
// 说明可以被2整除
return isUglyNumber(n / 2);
} else if (n % 3 == 0) {
// 说明可以被3整除
return isUglyNumber(n / 3);
} else if (n % 5 == 0) {
// 说明可以被5整除
return isUglyNumber(n / 5);
} else {
return false;
}
}
}