-1

I'm trying to use C++ to solve Project Euler problem 4.

I thought of placing each digit into an array and seeing if the values of the elements are the same in the correct places. This is what I have so far:

int digits[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

But I can't write the code. How can I take the number and make it seem that way? I know the basics of C++ (loops and pointers). How to use adjustable array in C++ and should I use this? I also don't know what the size of the array should be. Is there another better algorithm to implement?

4

5 回答 5

0

If you know array/string length you can loop and compare element [i] with element [length-i-1]

于 2013-07-12T00:15:42.220 回答
0

您可以使用循环来检查两端是否匹配:

int digits[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int length = sizeof(digits)/sizeof(digits[0]);
for (int i = 0; i < length; i++) {
    if (digit[i] != digits[length - i - 1])
        return false; // at this point, you know the number is not a palindrome 
return true;
于 2013-07-12T00:18:57.680 回答
0

长度计算有点类似于 C 的方法,但它确实有效。

#include <iostream>
using namespace std;

bool isPalindrome(int* digit_array, int len) {
    if(len <= 1) return true;
    if(digit_array[0] != digit_array[len-1])
        return false;
    else
        return isPalindrome(++digit_array, len-2);
}

int main() {
    int digits[] = {1, 2, 3, 4};
    int digits2[] = {1, 2, 2, 1};

    // it returns false
    cout << "isPalindrome(digits) => " << isPalindrome(digits, (sizeof(digits)/sizeof(*digits))) << endl;

    // it returns true
    cout << "isPalindrome(digits2) => " << isPalindrome(digits2, (sizeof(digits2)/sizeof(*digits2))) << endl;

    return 0;
}

编辑:我刚刚阅读了 Project Euler 问题 4。也许递归方法不是实现它的最佳方法。

于 2013-07-12T00:22:42.253 回答
0

我会将整数转换为字符串并检查字符串的反转是否等于自身。

#include <iostream>
#include <string>

int main()
{
    int num = 21334;
    auto s = std::to_string( num );

    if (std::string(s.begin(), s.end()) == std::string(s.rbegin(), s.rend()))
    {
        std::cout << "num is a palindrome";
    } else
    {
        std::cout << "num is not a palindrome";
    }
}
于 2013-07-12T00:35:29.380 回答
0

我希望你现在已经解决了这个问题,但是对于那些最近被难住的人来说,有一种更简单的方法可以在不弄乱字符串的情况下完成这个问题。您可以结合使用 mod 函数和除法(% 和 /)来单独查看每个数字。我解决这个问题的方法是向后构建数字,然后比较它们。这里的关键是要知道 number%10 会给你个位数字,然后 number/10 会砍掉个位数字。玩得开心,我真的很喜欢解决一些体育问题!

于 2013-10-16T21:04:08.020 回答