Java 返回第n个数字
我试图返回第n个数字。从1开始,如果一个数字是3或7的倍数,则跳过该数字,并取下一个数字。但是,如果该数字是3和7的倍数,则不会跳过该数字Java 返回第n个数字,java,Java,我试图返回第n个数字。从1开始,如果一个数字是3或7的倍数,则跳过该数字,并取下一个数字。但是,如果该数字是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 &&am
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 int-Multiple(int-num){
int n1=n%3;
int n2=n%7;
整数计数=1;
对于(inti=1;i我想你应该把下面两行放在循环中
int n1 = n % 3;
int n2 = n % 7;
另外,您的逻辑有点缺陷。当n1
和n2
均为零或均为非零时,您应该准确地递增计数器
int count = 0;
int i;
for (i = 1; count <= num; i++) {
int n1 = i % 3;
int n2 = i % 7;
if (n1 != 0 && n2 != 0)
count++;
else if (n1 == 0 && n2 == 0)
count++;
else // There is only one condition left. One is zero but the other is not.
continue;
}
return i;
int count=0;
int i;
对于(i=1;count如果您想要得到满足条件的第n个数字,则表示此代码可以正常运行
public int Multiple(int n){
int count=0;
for(int i=1;;i++)
{
if(i%3==0&&i%7==0)
{
count++;
}
else if(i%3==0||i%7==0)
continue;
else
{
count++;
}
if(count==n)
{
return i;
}
}
}这将完成以下工作:
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;
}
你自己解决这个问题会学到更多。这些数字是从什么来的?哦!!!((num%3==0)^(num%7==0))
有点难看。只需使用这个:((num%3==0)=(num%7==0))
我进一步改进了算法。现在它更简单了。
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