gpt4 book ai didi

java - 返回第 n 个数

转载 作者:行者123 更新时间:2023-11-29 05:24:58 29 4
gpt4 key购买 nike

我正在尝试返回第 n 个数字。如果数字是 3 或 7 的倍数,则从 1 开始,则跳过该数字并获取下一个数字。但是,如果数字是 3 和 7 的倍数,则不会跳过该数字。

public int Multiple(int num){
int n1 = n % 3;
int n2 = n % 7;
int count = 1;
for (int i = 1; i <= n; i++) {
if (n1 != 0 || n2 != 0)
count++;
if (n1 == 0 && n2 == 0)
count++;
else if (n1 == 0 || n2 == 0)
continue;
}
return count;
}

最佳答案

这将完成工作:

public static int nthNumber(int nth) {
int num = 1;
for (int count = 1; count < nth;) {
if ((++num % 3 == 0) == (num % 7 == 0)) count++;
}
return num;
}

前 20 个数字的输出:

 1 -> 1
2 -> 2
3 -> 4
4 -> 5
5 -> 8
6 -> 10
7 -> 11
8 -> 13
9 -> 16
10 -> 17
11 -> 19
12 -> 20
13 -> 21
14 -> 22
15 -> 23
16 -> 25
17 -> 26
18 -> 29
19 -> 31
20 -> 32

关于java - 返回第 n 个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23026490/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com