2022/12/20

LeetCode 9. Palindrome Number

問題:判斷是否為迴文
解法:先假設此文字為迴文,取得文字長度並除2取上限整數,將前後字元相比給予result 迴圈內任一結果不是立即中止,回傳結果 JavaScript
/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function (x) {
    const INT_MAX = Math.pow(2, 31) - 1;
    if (x > INT_MAX || x < -(x + 1) || x < 0) {
        return false;
    }

    let str = x.toString();
    const numLength = str.length;
    let result = true;
    for (let i = 0; i <= Math.ceil(numLength / 2); i++) {
        result = str.charAt(i) === str.charAt(numLength - i - 1)
        if (!result) {
            break;
        }
    }

    return result;
};