0

Fairly new to coding. Trying some of the easy projects at LeetCode, and failing... Ha! I am trying to take an integer and convert it to a string so I can reverse it, then re-convert the reversed string back into a integer.

This code is throwing the "terminate after throwing and instance of 'std::invalid argument' what(): stoi" error. I've spent an hour searching google and other questions here on SO, but can't figure out why it's not working.

bool isPalindrome(int x) {
  std::string backwards ="";
  std::string NumString = std::to_string(x);
     
  for (int i = NumString.size(); i >= 0 ; i--) {
    backwards += NumString[i];
  }
       
  int check = std::stoi(backwards);
              
  if (check == x) {
    return true;
  }
  else {
    return false;
  }
}

EDIT: I think I figured it out. It was adding the null character to the end of the string upon first conversion, then adding it to the beginning of the string when I reversed it. Spaces can't be converted to integers.

So... I changed this line and it works:

for (int i = NumString.size() - 1; i >= 0 ; i--) 
  • 4
    With `int i = NumString.size()` the index `i` will start out of bounds. – Some programmer dude Feb 26 '22 at 18:06
  • FYI: [std::reverse()](https://en.cppreference.com/w/cpp/algorithm/reverse) – 001 Feb 26 '22 at 18:10
  • 1
    *I've spent an hour searching google* -- You don't solve logic problems by doing google searches. You should [use the debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). – PaulMcKenzie Feb 26 '22 at 19:34
  • `std::string NumString = std::to_string(x); std::string NumString2 = NumString; std::reverse(NumString.begin(), NumString.end()); return NumString1 == NumString2;` – PaulMcKenzie Feb 26 '22 at 19:51

2 Answers2

0

you can also reverse number without using string.

     bool isPalindrome(int x) {
        long long  rev = 0;
        int cur = x;
        while( cur > 0) {
            rev *= 10;
            rev += cur % 10;
            cur /=10;
        }
        return rev == x;

    }
Tomáš Šturm
  • 489
  • 4
  • 8
0

Its simpler than your answer that you edited in. YOu have

  for (int i = NumString.size(); i >= 0 ; i--) {
    backwards += NumString[i];
  }
 

Imagine that Numstring has length 3 (no matter what spaces, digits,....)

So now you are efectively doing

  for (int i = 3; i >= 0 ; i--) {
    backwards += NumString[i];
  }
 

So first loop goes

  backwards += NumString[3];

well the indexes of things in an array of length 3 in c++ are 0,1,2. YOu are going one off the end

This is why you see loops doing

 for(int i = 0; i < len; i++){}

Note the i < len not i <= len

pm100
  • 48,078
  • 23
  • 82
  • 145