简体   繁体   English

C ++中的回文数

[英]Palindrome number in C++

I'm trying to write a C++ program to find if a number is a palindrome. 我正在尝试编写一个C ++程序来查找数字是否是回文。 Here's my code. 这是我的代码。 The problem is that the program returns false even when the number is a palindrome. 问题在于,即使数字是回文,程序也会返回false。

#include <cstdlib>
#include <iostream>
#include <string>

bool is_palindrome(int n){
  std::string num = std::to_string(n);
  int len = num.length();
  bool check = false;
  for(int i=0; i < len/2; i++){
    if(num[i] == num[len-i])
    check = true;
  }
  return check;
}

int main(){
   int num = 23232;
   std::cout<< is_palindrome(num) << std::endl;
   return 0;

}

What is my logic missing. 我缺少什么逻辑。

The maximum index of num array is len - 1 and not len . num数组的最大索引是len - 1而不是len So use: 所以使用:

if (num[i] == num[len - 1 - i])

to compare the first array index to the last array index, and so on. 比较第一个数组索引和最后一个数组索引,依此类推。

There is also another error since is_palindrome() will return true even if there is one coincidence (ie returns true if any 2 indices match). 还有另一个错误,因为即使有一个巧合, is_palindrome()也会返回true (即如果任何2个索引匹配则返回true )。 So when checked becomes true it never becomes false again. 因此,当checked变为true它再也不会变为false

You can finally change to: 你最终可以改为:

for (int i = 0; i < len/2; i++)
    if (num[i] != num[len - 1 - i])
        return false;

return true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM