Palindrome Number (E)
题目
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -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: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
题意
判断一个整数是否为回文数。
思路
不转换为字符串,直接对整数进行处理,有比较多的方法,如比较逆序后整数与输入的整数是否相同、将整数每一位拆分出来存进数组等。可以对第一个方法进行优化:不需要完全逆序,将逆序一半的整数和剩下的一半比较大小即可。
代码实现
Java
class Solution {
public boolean isPalindrome(int x) {
// 末尾为0且输入不为0是特殊情况,需要先排除
if (x < 0 || (x != 0 && x % 10 == 0)) {
return false;
}
int reverse = 0;
while (x > reverse) {
reverse = reverse * 10 + x %10;
x /= 10;
}
// 有奇偶两种情况
return x == reverse || x == reverse / 10;
}
}
JavaScript
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function (x) {
if (x < 0 || (x !== 0 && x % 10 === 0)) return false
let y = 0
while (x > y) {
y = y * 10 + (x % 10)
x = Math.trunc(x / 10)
}
return x === y || x === Math.trunc(y / 10)
}