Palindrome Number

Leetcode solutions in c#

Table of contents

No heading

No headings in the article.

Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward.

For example, 121 is a palindrome while 123 is not.

Example 1:

Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left. Example 2:

Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3:

Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Constraints:

-231 <= x <= 231 - 1

Approach: First reverse the number Then compare the new number with the old one if same then return true else false

Code:

using System;

namespace Palindrome
{
    class Program
    {

        public bool IsPalindrome(int x)
        {
            bool b = false;
            int r = 0; //Taking the r variable to save the reverse of the number
            int n = x; //Taking New n variable to save the value of the number
            while (x > 0) //reverse the number
            {
                int reminder = x % 10;
                r = r * 10 + reminder;
                x = x / 10;
            }
            if (r == n) //compare the reversed number with the old number
            {
                b = true;
            }

            return b;
        }
        static void Main(string[] args)
        {
            int x = int.Parse(Console.ReadLine());//taking the input and converting the string to int

            Program obj = new Program();//creating the instance of program class
            bool k = obj.IsPalindrome(x);
            Console.WriteLine(k);// prints true or false

        }
    }
}