错误的答案调用回文
Wrong answer calls on palindrome
我编写了回文程序。
我认为这段代码是正确的,尤其是 is_palindrome 程序。
但是不知道为什么这个回答错了
因为我输入2 1 1的时候,return一定是This is palindrome。
但它回答了另一个。
#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;
}
C++ 中的数组索引为零,因为 i
被初始化为 0
,在循环的第一次迭代中 input[numOfSlots-i]
超出范围。
您将经过 if (input[i] != input[numOfSlots-i])
中的数组末尾。当 i == 0
时,input[numOfSlots-i]
变为 input[numOfSlots]
,在本例中为 input[2]
。由于 input
的最后一个有效索引是 1,因此您正在与垃圾进行比较。你应该
if (input[i] != input[numOfSlots-i - 1])
我编写了回文程序。 我认为这段代码是正确的,尤其是 is_palindrome 程序。 但是不知道为什么这个回答错了
因为我输入2 1 1的时候,return一定是This is palindrome。 但它回答了另一个。
#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;
}
C++ 中的数组索引为零,因为 i
被初始化为 0
,在循环的第一次迭代中 input[numOfSlots-i]
超出范围。
您将经过 if (input[i] != input[numOfSlots-i])
中的数组末尾。当 i == 0
时,input[numOfSlots-i]
变为 input[numOfSlots]
,在本例中为 input[2]
。由于 input
的最后一个有效索引是 1,因此您正在与垃圾进行比较。你应该
if (input[i] != input[numOfSlots-i - 1])