Spread the love

Problem Description

Given an integer x, return true if x is a palindrome, and false otherwise.


Given an integer x, the task is to determine if it is a palindrome. A palindrome is a number that remains the same when its digits are reversed. For example, 121 is a palindrome, but 123 is not.

Solution

The solution to this problem involves converting the integer to a string, then checking if the string is equal to its reverse.

Algorithm

  1. Convert the integer to a string
  2. Reverse the string
  3. Compare the original string to the reversed string
  4. If the strings are equal, return true
  5. If the strings are not equal, return false

C#

public bool IsPalindrome(int x) {
    string original = x.ToString();
    char[] reversed = original.Reverse().ToArray();
    return original == new string(reversed);
}

Java

public boolean isPalindrome(int x) {
    String original = Integer.toString(x);
    String reversed = new StringBuilder(original).reverse().toString();
    return original.equals(reversed);
}

C++

bool isPalindrome(int x) {
    std::string original = std::to_string(x);
    std::string reversed = original;
    std::reverse(reversed.begin(), reversed.end());
    return original == reversed;
}

Python

def is_palindrome(x):
    original = str(x)
    reversed = original[::-1]
    return original == reversed

Time Complexity:

The time complexity of both the C# and Java solutions is O(n), where n is the number of digits in the integer. This is because we are converting the integer to a string and reversing the string, both of which take O(n) time.

Conclusion

In this blog, we have seen how to determine if a given integer is a palindrome. By converting the integer to a string, reversing the string, and comparing the two, we can easily determine if the number is a palindrome. Both the C# and Java solutions have a time complexity of O(n), making them efficient solutions for this problem.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *