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

Ugly Number II

时间:2016-10-24 09:30:02      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:sequence   pos   example   div   style   math   who   number   prim   

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.

 

3 pointer index2, index3, index5

public class Solution {
    public int nthUglyNumber(int n) {
        int isUglyNum[] = new int[n];
        isUglyNum[0] = 1;
        int count = 1;
        int index2 = 0;
        int index3 = 0;
        int index5 = 0;
        while(count < n){
            isUglyNum[count] = Math.min(isUglyNum[index2] * 2, Math.min(isUglyNum[index3] * 3, isUglyNum[index5] * 5));
            if(isUglyNum[count] == isUglyNum[index2] * 2)
                index2 ++;
            if(isUglyNum[count] == isUglyNum[index3] * 3)
                index3 ++;
            if(isUglyNum[count] == isUglyNum[index5] * 5)
                index5 ++;
            count++;
        }
        return isUglyNum[n-1];
    }
    
}

 

Ugly Number II

标签:sequence   pos   example   div   style   math   who   number   prim   

原文地址:http://www.cnblogs.com/joannacode/p/5991684.html

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