Leetcode 263-264 ugly number

8 篇文章 0 订阅
6 篇文章 0 订阅

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.

题意:确定一个数是不是“ugly number”。

题解:简单,直接看代码:

public class Solution { 
public boolean isUgly(int num) { 
if(num<=0) return false; 
while(num!=1) 
{ if((num%5!=0)&&(num%3!=0)&&(num%2!=0)) return false; 
if(num%5==0) num/=5; 
if(num%3==0) num/=3; 
if(num%2==0) num/=2; 
} 
return true; 
} 
} 

这题有意思一点的是其follow up。
Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

即找出第n个ugly number。朴素求解方法是对于每一个数,判断其是不是ugly number,然后数字加一,继续判断,显然效率极差。我们可以从如何构造ugly number 入手。
注意到ugly number为n=(2^i)(3^j)(5^k),所以有以下序列:

1  2x1,2x2,2x3,2x4...
2  3x1,3x2,3x3,3x4...
3  5x1,5x2,5x3,5x4...

为了维护ugly number的有序性,可以归并以上三个序列,逐次取最小值。详细的分析见代码及注释:

public class Solution {
    public int min(int a,int b,int c)//求三个数最小值
    {
        int Min=a>b? b:a;
        return Min>c? c:Min;
    }
    public int nthUglyNumber(int n) {
        int[] s=new int[n];
        s[0]=1;//第一个ugly number
        int factor2=2,factor3=3,factor5=5;//每个列表的当前比对值
        int i,j,k;//三个列表的index
        i=j=k=0;//初始化为0
        for(int p=1;p<n;p++)
        {
          int Min_num=min(factor2,factor3,factor5);//取三个列表的当前值重最小那个
          s[p]=Min_num;
          if(Min_num==factor2)//如果是factor2,则更新factor2的值
            factor2=2*s[++i];
          if(Min_num==factor3)//同上
            factor3=3*s[++j];
          if(Min_num==factor5)//同上
            factor5=5*s[++k];
        }
        return s[n-1];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值