Palindrome Integer in C++

C++Server Side ProgrammingProgramming

Suppose we have a non-negative integer called num, we have to check whether it is a palindrome or not, but not using a string.

So, if the input is like 1331, then the output will be true.

To solve this, we will follow these steps −

  • ret := 0

  • x := num

  • while num > 0, do −

    • d := num mod 10

    • ret := ret * 10

    • ret := ret + d

    • num := num / 10

  • return true when x is same as ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool solve(int num) {
      int ret = 0;
      int x = num;
      while(num > 0){
         int d = num % 10;
         ret *= 10;
         ret += d;
         num /= 10;
      }
      return x == ret;
   }
};
main() {
   Solution ob;
   cout << (ob.solve(1331));
}

Input

1331

Output

1
raja
Published on 02-Sep-2020 11:41:59
Advertisements