Hi everybody!
I am working on a program, that tells wether a number is palindromic, and in my opinion, the code i have pasted works perfectly for such purpose. However, when I submit it for an online correction, it seems that for some number(s) it doesen't work.
Note: The number will always be natural.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <iostream>
#include <vector>
using namespace std;
bool is_palindromic (int n) {
bool b = false;
//vector to store the digits of n in a reversed way
vector<int> coefs;
//store the value of n
int z = n;
//put the digits of n in the vector in a reversed order
while (n != 0) {
coefs.push_back(n%10);
n = n/10;
}
//check wether the vector matches the number
int t;
int a = coefs.size();
for (int i = 0; i < a; ++i) {
if (coefs[a-1-i] == z%10) ++t;
z = z/10;
}
if (t == a) b = true;
return b;
}
int main () {
int n;
while (cin >> n) {
if (is_palindromic(n)) cout << "YES";
else cout << "NO";
cout << endl;
}
}
|
Brief explanation:
Once the number has been entered, i use the command push_back to store each digit of the number in a vector in a reversed order as well as to get the size of the digit by increasing a variable by 1 each time the while loop is executed.
Once the number is in the vector, I use a for to check whether the digits of the vector (starting from the end of the vector, which is the beginning of the number) match the digits from the number. If this happens, a counter is increased. At the end, if the counter equals the size of the vector it means that all the numbers were the same, so the value returned is true.
I certainly don't know why it doesen't work, I hope that someone can help me.
Thanks to anyone that took the time to read the post, I appreciate it!
Have a nice day!