34 ugly numbers

A number containing only the factors 2, 3 and 5 is called an Ugly Number. For example, 6 and 8 are ugly numbers, but 14 is not because it contains the factor 7. Traditionally we treat 1 as the first ugly number. Find the Nth ugly number in ascending order

 

Java:

 1 public class Solution {
 2     public int GetUglyNumber_Solution(int index) {
 3         if (index <= 6)
 4             return index ;
 5         int i2 = 0 , i3 = 0 , i5 = 0 ;
 6         int[] dp = new int[index] ;
 7         dp[0] = 1 ;
 8         for(int i = 1 ; i < index ; i++){
 9             int n2 = dp[i2]*2 , n3 = dp[i3]*3 , n5 = dp[i5]*5 ;
10             dp[i] = Math.min(n2 , Math.min(n3,n5)) ;
11             if (dp[i] == n2)
12                 i2++ ;
13             if (dp[i] == n3)
14                 i3++ ;
15             if (dp[i] == n5)
16                 i5++ ;
17         }
18         return dp[index-1];
19     }
20 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325944045&siteId=291194637