2016-01-27 61 views
-1

我編碼的迴文項目。 我覺得這段代碼尤其適合is_palindrome程序。 但我不知道爲什麼這個答案錯了​​。迴文錯誤答案電話

因爲當我輸入2 1 1時,必須返回這是迴文。 但它回答了另一個。

#include <iostream> 
using namespace std; 

bool is_palindrome(int input[], int numOfSlots); 

int main(void) { 
    int n; 
    cin >> n; 
    int *input = new int[n]; // A dynamic array with n slots 
    for (int i = 0; i < n; i++) { 
     cin >> input[i]; 
    } 

    if (is_palindrome(input, n) == true) { 
     cout << "This is a palindrome."; 
    } 
    else { 
     cout << "This is NOT a palindrome."; 
    } 
    return 0; 
} 

bool is_palindrome(int input[], int numOfSlots) { 
    int i = 0; 
    while (i < numOfSlots/2) 
    { 
     if (input[i] != input[numOfSlots-i]) 
      return false; 
     i++; 
    } 
    return true; 
} 
+1

'2 1 1'不是迴文,是嗎? – zaratustra

+0

@zaratustra 2表示數組的大小。實際的比較發生在'1 1'部分。 – NathanOliver

+0

你有內存泄漏。如果你寫'std :: vector input(n);'(並進行其他必要的更改)它將消失。你也可以寫'bool is_palindrome(const std :: vector &input)',而不必單獨傳遞大小。作爲一般規則,避免使用赤裸裸的'new' - 總是在'std :: make_unique','std :: vector'或'std :: make_shared'封裝你的內存分配(在極少數情況下你需要後者)。 –

回答

2

您將會在if (input[i] != input[numOfSlots-i])之後的數組結束。當i == 0然後input[numOfSlots-i]變成input[numOfSlots],在這種情況下是input[2]。由於input的最後一個有效索引爲1,因此您正在比較垃圾。你應該有

if (input[i] != input[numOfSlots-i - 1]) 
2

陣列in C++是零索引,如i初始化爲0,環路上input[numOfSlots-i]的第一次迭代是出界。