Palindrome Number

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

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:

  • -2<sup>31</sup> <= x <= 2<sup>31</sup> - 1

Solution

Initial Solution was to use the default "Reverse" function of C#

public class Solution {
    public bool IsPalindrome(int x) {
        return string.Concat(x.ToString().Reverse()) == x.ToString();
    }
}

This had a Runtime of 65 ms and Memory of 37.92 MB

Another solution is to convert it into array of characters and reversing the array.

public class Solution {
    public bool IsPalindrome(int x) {
        string strNumber = "";
        string strReversed = "";

        strNumber = x.ToString();
        char[] charArray = strNumber.ToCharArray();
        Array.Reverse(charArray);
        strReversed = new string(charArray);
        if(strNumber == strReversed)
            return true;
        else
            return false;
    }
}

This had a Runtime of 36 ms and Memory of 34.17 MB

Here's how the code works step-by-step:

  1. Converting the number to a string:

    • strNumber = x.ToString();: This line converts the integer x to a string and stores it in the variable strNumber. This is necessary because we need to compare individual digits of the number, which is easier to do with strings.
  2. Reversing the string:

    • charArray = strNumber.ToCharArray();: This line converts the string strNumber into an array of characters, where each character is a separate element in the array.

    • Array.Reverse(charArray);: This line reverses the order of the characters in the array.

    • strReversed = new string(charArray);: This line creates a new string from the reversed character array and stores it in the variable strReversed.

  3. Checking for palindrome:

    • if(strNumber == strReversed): This line compares the original string strNumber with the reversed string strReversed. If they are equal, it means the number is a palindrome.

In simpler terms:

The code first converts the number to a string, then reverses the order of its digits. Finally, it compares the original and reversed strings to see if they are the same. If they are, the number is a palindrome; otherwise, it's not.

0
Subscribe to my newsletter

Read articles from Edward Anil Joseph directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Edward Anil Joseph
Edward Anil Joseph