leetcode-cn.com/problems/ug…

Answer:

  1. Using three nested loops, calculate all possible ugly numbers.
  2. Because each layer of the loop is evaluated based on the results of the upper loop, the results are not sorted.
  3. Order all the ugly numbers from smallest to largest, and then pick the NTH one.
/ * * *@param {number} n
 * @return {number}* /
var nthUglyNumber = function (n) {
  let ugly = []; // Store all ugly numbers

  // Enumerate all numbers with prime factors of 2, 3, and 5 respectively and store them in array
  / / 0 x7fffffff is the biggest 32 bit binary number, namely 0 b1111111111111111111111111111111
  // This corresponds to the base 10 number 2147483647
  for (let i = 1; i <= 0x7fffffff; i *= 2) {
    for (let j = i; j <= 0x7fffffff; j *= 3) {
      for (let k = j; k <= 0x7fffffff; k *= 5) { ugly.push(k); }}}// Because each layer of the loop is based on the result of the upper loop, for example, in the case of I and j are equal to 1, all the results of k*=5 are calculated first
  // The ugliness calculated by this method is not sorted by size, so all the ugliness can only be calculated and sorted to get the desired value
  ugly.sort((a, b) = > a - b);

  // Fetch the NTH ugly number
  return ugly[n - 1];
};
Copy the code