Java Solution for https://leetcode.com/problems/palindrome-number/
As per the problem we have been given an integer and we need to check if it is palindromic or not.
input_x = 121 reversed_x = 121 input_x and reversed_x are palindromic input_x = -121 reversed_x = 121- input_x and reversed_x are not palindromic
My Thought About Solution
- The solution looks pretty easy for me, we just have to read input integer digits backward and construct reversed integers.
- Then we can compare the input integer and reversed integer and return the result.
- One additional optimization we can do is that we can return negative integers without even checking if its palindromic or not since negative signs will make them not palindromic.
- Data structure: We are not using any collection, just integer is enough to hold the data.
Time-complexity: O(length(N)) where N is the input integer
Space-complexity: O(1) constant space
1: First check if input integer is negative , if yes the return false , since input integers cannon be palindromic due do - sign 2: Construct reversed input integer by reading from last digit and append to reversed integer 3: Now compare the input integers and return the result
Our Code Runtime beats 99.96% of the submission. Nice job!
This Leetcode is a good problem to understand
- How to iterate over each digit in integer and play around with it.
- Optimizing solution by finding out cases where we don’t need to perform our core business logic.
Let me know if you have some opinion on the solution in the comment!