Preface explains
Algorithm learning, daily brush record.
Subject to connect
palindrome
The subject content
Given an integer x, return true if x is a palindrome integer; Otherwise, return false.
Palindromes are integers that read in positive (left to right) and backward (right to left) order. For example, 121 is palindrome and 123 is not.
Example 1:
Enter: x = 121
Output: true,
Example 2:
Enter: x = -121
Output: false
Interpretation: Read from left to right as -121. Read from right to left, 121-. So it’s not a palindrome number.
Example 3:
Enter: x = 10
Output: false
Interpretation: Read from right to left as 01. So it’s not a palindrome number.
Example 4:
Enter: x = -101
Output: false
Tip:
-2^31 <= x <= 2^31 – 1
The analysis process
By iterating through the input number, construct the inverted number.
Define the inverted number sum, initialized to 0.
In each loop, the current number mod 10 to get the last digit m, and sum is multiplied by 10 plus m to get the current inverted number. Divide the current number by 10 to get the last digit.
Finally, sum is summed to get the inverted number.
If the inverted number sum is equal to the original number x, then the number is a palindrome.
To solve the code
class Solution { public boolean isPalindrome(int x) { if (x < 0) { return false; } else { int n = x; int sum = 0; While (x > 0) {int m = x % 10; sum = sum * 10 + m; x = x / 10; } return n == sum; }}}Copy the code
Submit the results
It took 10ms to execute, beating 70.61% of users in time, 37.9MB in memory consumption, and 48.39% in space.
The original link
Palindrome number