首页 > 代码库 > 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
. 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。