Posts

Showing posts with the label Ugly Number II

Ugly Number II

Write a program to find the n -th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5 .  Example: Input: n = 10 Output: 12 Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. Note:   1 is typically treated as an ugly number. n does not exceed 1690 .   class Solution {         public int nthUglyNumber(int n) {             int[] ugly = new int[n];             ugly[0] = 1;             int indexOf2 = 0, indexOf3 = 0, indexOf5 = 0;             int factorOf2 = 2, factorOf3 = 3, factorOf5 = 5;             for(int i=1;i<n;i++){                 int min = Math.min(Math.min(factorOf2,factorOf3),factorOf5);                 ugly[i] = min;                 if(factorOf2 == min)                     factorOf2 = 2*ugly[++indexOf2];                 if(factorOf3 == min)                     factorOf3 = 3*ugly[++indexOf3];                 if(factorOf5 == min)                     factorOf5 = 5*ugly[++