Search code examples
c++algorithmc++11palindrome

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. 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];
    }

Solution

  • I think you need to return true in isPalindrome after comparing complete string. ie return true; should be outside for loop

    And for checking largest 3 digit palindrome why are you passing int pal = i*j; ie for first iteration 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;
      }
    }