2014-04-12 72 views
1

我想返回第n个号码。如果数字是3或7的倍数,则从1开始,然后跳过该号码并采取下一个号码。但是,如果该数字是3和7的倍数,则该数字不会被跳过。返回第n个号码

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; 
} 
+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号OUTPUT:

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 
+0

'!((num%3 == 0)^(num%7 == 0))'有点儿丑。只需使用: '((num%3 == 0)==(num%7 == 0))' – Obicere

+0

@Obicere是啊,好多了:) thx! – Harmlezz

+0

我进一步改进了算法。现在它更加简单。 – Harmlezz

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

如果你想获得第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; 
     } 

    } 

}

+0

这些数字来自哪里?喔! –

+0

我编辑过,请看那里。 –