21xrx.com
2025-03-22 04:01:11 Saturday
文章检索 我的文章 写文章
如何在C++中判断一个数是否为回文数
2023-06-23 20:38:24 深夜i     22     0
C++ 回文数 判断

回文数是指正序和倒序都相同的整数,如121和1221。在C++中,判断一个数是否为回文数可以通过以下方法实现:

1. 将整数转换成字符串类型,然后反转字符串,比较反转后的字符串是否和原字符串相等。如果相等,则该整数是回文数。以下是示例代码:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isPalindrome(int x) {
  string str = to_string(x);
  string reverse_str = str;
  reverse(reverse_str.begin(), reverse_str.end());
  return str == reverse_str;
}
int main() {
  int x = 121;
  if (isPalindrome(x))
    cout << "The number is a palindrome." << endl;
  
  else
    cout << "The number is not a palindrome." << endl;
  
  return 0;
}

2. 利用数字的数学特性,将整数从中间分开,将左半部分和右半部分分别反转,然后比较两者是否相等。以下是示例代码:

bool isPalindrome(int x) {
  // 排除负数和以0结尾的数
  if (x == 0)
    return true;
  
  if (x < 0 || x % 10 == 0)
    return false;
  
  int right_half = 0;
  while (x > right_half) {
    right_half = right_half * 10 + x % 10;
    x /= 10;
  }
  // 如果x为偶数位数,则x==right_half
  // 如果x为奇数位数,则x==right_half/10
  return x == right_half || x == right_half / 10;
}
int main() {
  int x = 121;
  if (isPalindrome(x))
    cout << "The number is a palindrome." << endl;
  
  else
    cout << "The number is not a palindrome." << endl;
  
  return 0;
}

以上两种方法都可以用来判断一个数是否为回文数。第一种方法通过字符串操作实现,适用于小范围的数字判断;第二种方法通过数学特性实现,适用于大范围的数字判断。具体选择哪种方法取决于使用场景和具体需求。

  
  

评论区

请求出错了