Palindrome数字在C ++ [英] Palindrome number in C++
问题描述
我想写一个C ++程序来查找一个数字是否是一个回文。这是我的代码。问题是,即使数字是回文,程序返回false。
I'm trying to write a C++ program to find if a number is a palindrome. Here's my code. The problem is that the program returns false even when the number is a palindrome.
#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;
}
我的逻辑是什么?
推荐答案
num数组的最大索引为 len - 1
len
。所以使用:
The maximum index of num array is len - 1
and not len
. So use:
if (num[i] == num[len - 1 - i])
来比较第一个数组索引与最后一个数组索引,等等。
to compare the first array index to the last array index, and so on.
还有另一个错误,因为 is_palindrome()
将返回 true
,即使有一个巧合如果任何2个索引匹配,则返回 true
)。因此,当检查
变为 true
时,它不会再次变为 false
There is also another error since is_palindrome()
will return true
even if there is one coincidence (i.e returns true
if any 2 indices match). So when checked
becomes true
it never becomes false
again.
您最后可以更改为:
for (int i = 0; i < len/2; i++)
if (num[i] != num[len - 1 - i])
return false;
return true;
这篇关于Palindrome数字在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!