c++ - Wrong answer calls on palindrome -
i coded palindrome program. think code right is_palindrome procedure. don't know why answers wrong.
because when input 2 1 1, return must palindrome. answers other.
#include <iostream> using namespace std; bool is_palindrome(int input[], int numofslots); int main(void) { int n; cin >> n; int *input = new int[n]; // dynamic array n slots (int = 0; < n; i++) { cin >> input[i]; } if (is_palindrome(input, n) == true) { cout << "this palindrome."; } else { cout << "this not palindrome."; } return 0; } bool is_palindrome(int input[], int numofslots) { int = 0; while (i < numofslots/2) { if (input[i] != input[numofslots-i]) return false; i++; } return true; }
you going 1 past end of array in if (input[i] != input[numofslots-i])
. when i == 0
input[numofslots-i]
becomes input[numofslots]
in case input[2]
. since last valid index of input
1 comparing against garbage. should have
if (input[i] != input[numofslots-i - 1])
Comments
Post a Comment