码迷,mamicode.com
首页 > 其他好文 > 详细

Ugly Number

时间:2015-09-21 11:59:32      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

import java.util.ArrayList;

/**
* Created by seven_hu on 2015/9/21.
*/

public class Solution3 {
/*
*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.
*
* */
public boolean isUgly(int num){
if(num==1) return true;
while(num%2==0) num=num/2;
while(num%3==0) num=num/3;
while(num%5==0) num=num/5;
return num==1;
}
/*
*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.
*
* */
public int nthUglyNum(int n){
if(n<1){
return 0;
}
int id2=0;
int id3=0;
int id5=0;
int rst=1;
ArrayList<Integer> arr=new ArrayList();
while(n>0){
arr.add(rst);
int v2=2*(arr.get(id2));
int v3=3*(arr.get(id3));
int v5=5*(arr.get(id5));
rst=Math.min(v2,Math.min(v3,v5));
if(rst==v2){
id2=id2+1;
}
if(rst==v3){
id3=id3+1;
}
if(rst==v5){
id5=id5+1;
}

}
return rst;
}
}

Ugly Number

标签:

原文地址:http://www.cnblogs.com/hujingwei/p/4825646.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!