zoukankan      html  css  js  c++  java
  • 剑指Offer(Java版)第三十八题:把只包含质因子2、3和5的数称作丑数(Ugly Number)。 例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。 求按从小到大的顺序的第N个丑数。

    /*
    把只包含质因子2、3和5的数称作丑数(Ugly Number)。
    例如6、8都是丑数,但14不是,因为它包含质因子7。
    习惯上我们把1当做是第一个丑数。
    求按从小到大的顺序的第N个丑数。
    */
    public class Class38 {

    public int GetUglyNumber_Solution(int index){
    if(index <= 0){
    return 0;
    }
    int count = 0;
    int uglyNumber = 0;
    int start = 1;
    while(count < index){
    if(findUglyNumber(start) == true){
    uglyNumber = start;
    count++;
    start++;
    }else{
    start++;
    }
    }
    return uglyNumber;
    }

    public boolean findUglyNumber(int index){
    if(index <= 0){
    return false;
    }
    while(true){
    if(index == 1 || index == 2 || index == 3 || index == 5){
    return true;
    }else if(index % 2 == 0){
    index /= 2;
    }else if(index % 3 == 0){
    index /= 3;
    }else if(index % 5 == 0){
    index /= 5;
    }else{
    return false;
    }
    }
    }
    public void test(){
    int index = 20;
    System.out.println(GetUglyNumber_Solution(index));
    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Class38 c = new Class38();
    c.test();

    }

    }

  • 相关阅读:
    几种常用的曲线
    0188. Best Time to Buy and Sell Stock IV (H)
    0074. Search a 2D Matrix (M)
    0189. Rotate Array (E)
    0148. Sort List (M)
    0859. Buddy Strings (E)
    0316. Remove Duplicate Letters (M)
    0452. Minimum Number of Arrows to Burst Balloons (M)
    0449. Serialize and Deserialize BST (M)
    0704. Binary Search (E)
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12517775.html
Copyright © 2011-2022 走看看