Ugly NumberⅡ
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.
JavaScript
/** * @param {number} n * @return {number} */ var nthUglyNumber = function(n) { var l1 = new Array(0), l2 = new Array(0), l3 = new Array(0), i = 0, ans = 0; l1[0] = 1; l2[0] = 1; l3[0] = 1; for(i = 0;i < n;i ++){ ans = Math.min(Math.min(l1[0],l2[0]),l3[0]); if(l1[0] === ans){ l1.shift(); } if(l2[0] === ans){ l2.shift(); } if(l3[0] === ans){ l3.shift(); } l1.push(ans * 2); l2.push(ans * 3); l3.push(ans * 5); } return ans; };
Java
public class Solution { public int nthUglyNumber(int n) { int u = 0; List<Integer> l1 = new LinkedList<Integer>(); List<Integer> l2 = new LinkedList<Integer>(); List<Integer> l3 = new LinkedList<Integer>(); l1.add(1); l2.add(1); l3.add(1); for(int i=0; i<n; i++) { u = Math.min( Math.min(l1.get(0), l2.get(0)), l3.get(0)); if(l1.get(0) == u) l1.remove(0); if(l2.get(0) == u) l2.remove(0); if(l3.get(0) == u) l3.remove(0); l1.add(u*2); l2.add(u*3); l3.add(u*5); } return u; } }
Ugly Number:
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 6, 8
are ugly while 14
is not ugly since it includes another prime factor 7
.
Note that 1
is typically treated as an ugly number.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
JavaScript
/** * @param {number} num * @return {boolean} */ var isUgly = function(num) { var i = 2; var temp = num; if(num <= 0) return false; if(num <= 6) return true; while(i * i <= num){ if(num % i === 0){ if(i > 5) return false; while(num % i === 0) num = num / i; } i ++; } if(num > 5) return false; return true; };