简体   繁体   English

最大回文3位C ++

[英]Largest Palindrome 3 digits C++

I cannot figure out why this code isn't working. 我不知道为什么此代码无法正常工作。 It doesn't even seem to be going through my for loops and nested loops. 它甚至似乎都没有经过我的for循环和嵌套循环。 I'm very new to programing. 我是编程的新手。 I have been trying to answer Euler questions for practice. 我一直在尝试回答欧拉的练习题。 Sorry if my code is awful. 抱歉,我的代码太糟糕了。

 #include <iostream>
    #include <string>
    using namespace std;

    bool isPalindrome(int x) {
        string str = to_string(x);

        for(string::reverse_iterator rit=str.rbegin(); rit!=str.rend(); ++rit) {
            string pal = to_string(*rit);
            if(pal == str) {
                return true;
            }else {
                return false;
            }
        }
    }

    int main() {
        int max[] = {0, 0};


        for(int i=999; i>99; i--) {
            for( int j =999; j>99; j--) {
            int pal = i*j;
                if(isPalindrome(pal) == true) {
                max[1] = pal;
                if(max[1] > max[0]){
                    max[0] = pal;
                    }
                }
            }
        }
        cout << max[0];
    }

I think you need to return true in isPalindrome after comparing complete string. 我认为您需要在比较完整字符串后在isPalindrome返回true。 ie return true; return true; should be outside for loop 应该是外面for

And for checking largest 3 digit palindrome why are you passing int pal = i*j; 为了检查最大的3位数回文,为什么要传递int pal = i*j; ie for first iteration 999*999 . 即对于第一次迭代999*999 Check this 检查一下

bool isPalindrome(int x) {
string str = to_string(x);
string pal = str;
std::reverse(pal.begin(),pal.end()); 

  if(pal == str) {
      return true;
  }else {
      return false;
  }
}

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

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