
一个只有2、3或5作为质因数的数被称为丑数。一些丑数包括:1、2、3、4、5、6、8、10、12、15等。
我们有一个数N,任务是在丑数序列中找到第N个丑数。
例如:
输入-1:
立即学习“Java免费学习笔记(深入)”;
N = 5
输出:
5
Explanation:
The 5th ugly number in the sequence of ugly numbers [1, 2, 3, 4, 5, 6, 8, 10, 12, 15] is 5.
PHP经典实例(第2版)能够为您节省宝贵的Web开发时间。有了这些针对真实问题的解决方案放在手边,大多数编程难题都会迎刃而解。《PHP经典实例(第2版)》将PHP的特性与经典实例丛书的独特形式组合到一起,足以帮您成功地构建跨浏览器的Web应用程序。在这个修订版中,您可以更加方便地找到各种编程问题的解决方案,《PHP经典实例(第2版)》中内容涵盖了:表单处理;Session管理;数据库交互;使用We
453
Input-2:
N = 7
输出:
8
解释:
在丑数序列[1, 2, 3, 4, 5, 6, 8, 10, 12, 15]中,第7个丑数是8。
解决这个问题的一个简单方法是检查给定的数字是否可以被2、3或5整除,并跟踪序列直到给定的数字。现在找到数字是否满足所有丑数的条件,然后将该数字作为输出返回。
演示
public class UglyN {
public static boolean isUglyNumber(int num) {
boolean x = true;
while (num != 1) {
if (num % 5 == 0) {
num /= 5;
}
else if (num % 3 == 0) {
num /= 3;
}
// To check if number is divisible by 2 or not
else if (num % 2 == 0) {
num /= 2;
}
else {
x = false;
break;
}
}
return x;
}
public static int nthUglyNumber(int n) {
int i = 1;
int count = 1;
while (n > count) {
i++;
if (isUglyNumber(i)) {
count++;
}
}
return i;
}
public static void main(String[] args) {
int number = 100;
int no = nthUglyNumber(number);
System.out.println("The Ugly no. at position " + number + " is " + no);
}
}The Ugly no. at position 100 is 1536.
以上就是在Java中找到第N个丑数的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号