2014-04-12 70 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

我編輯過,請看那裏。 –