用c++,且要用 using namespace std;
时间: 2023-09-27 22:06:12 浏览: 41
好的,这里是使用 `using namespace std` 的 C++ 版本的递归和迭代函数来检查整数是否为回文数的代码:
递归函数:
```cpp
#include <iostream>
using namespace std;
bool is_palindrome_rec(int num) {
string str_num = to_string(num);
if (str_num.length() <= 1) {
return true;
} else if (str_num[0] != str_num[str_num.length()-1]) {
return false;
} else {
return is_palindrome_rec(stoi(str_num.substr(1, str_num.length()-2)));
}
}
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
if (is_palindrome_rec(num)) {
cout << num << " is a palindrome (recursive)" << endl;
} else {
cout << num << " is not a palindrome (recursive)" << endl;
}
return 0;
}
```
迭代函数:
```cpp
#include <iostream>
using namespace std;
bool is_palindrome_iter(int num) {
string str_num = to_string(num);
for (int i = 0; i < str_num.length()/2; i++) {
if (str_num[i] != str_num[str_num.length()-1-i]) {
return false;
}
}
return true;
}
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
if (is_palindrome_iter(num)) {
cout << num << " is a palindrome (iterative)" << endl;
} else {
cout << num << " is not a palindrome (iterative)" << endl;
}
return 0;
}
```
希望能帮到你!