• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
seven_hu
博客园    首页    新随笔    联系   管理    订阅  订阅

Ugly Number

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;
}
}
posted @ 2015-09-21 11:31  seven_hu  阅读(168)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3