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)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/45361.html
標籤:其他
