判斷一個整數是否為迴文
阿新 • • 發佈:2021-01-10
題目說明
編寫C++程式碼,判斷一個整數是否是迴文(迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數) 例如:從左向右讀, 為 -121 。 從右向左讀, 為 121- 。因此它不是一個迴文數 程式碼實現利用兩個向量,用來儲存正序的整數的位數,分別兩個向量一個從前向後一個從後向前比較。程式碼
#include<iostream> #include<vector> using namespace std; vector<int> pos; vector<int> neg; //判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數 //從左向右讀, 為 -121 。 從右向左讀, 為 121- 。因此它不是一個迴文數 void Palindrome(const int num) { int number = num; if (num < 0) { cout << num << "不是迴文!" << endl; } else if (num < 10) { cout << num << "是迴文!" << endl; } else { while (number) { pos.push_back(number % 10); neg.push_back(number % 10); number = number / 10; } for (int i = 0; i < pos.size() ; i++) { if (neg.front() == pos.back()) { neg.erase(neg.begin()); pos.pop_back(); } else { cout << num << "不是迴文!" << endl; return; } } cout << num << "是迴文!" << endl; } } int main() { int num = 0; cout << "請輸入要判斷的數字:"; cin >> num; Palindrome(num); return 0; }