返回第n个数字

时间:2014-04-12 05:27:09

标签: java

我正在尝试返回第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;
}

3 个答案:

答案 0 :(得分:1)

我想你想把以下两行放在循环中。

int n1 = n % 3;
int n2 = n % 7;

另外,你的逻辑有点缺陷。当n1n2均为零或非零时,您应该完全递增计数器。

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;

答案 1 :(得分:1)

如果你想获得满足条件的第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;
         }

     }

}

答案 2 :(得分:1)

这将完成这项工作:

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