Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第九题 - 回文数 #10

Open
laizimo opened this issue May 26, 2020 · 0 comments
Open

第九题 - 回文数 #10

laizimo opened this issue May 26, 2020 · 0 comments

Comments

@laizimo
Copy link
Owner

laizimo commented May 26, 2020

题目描述

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:
输入: 121
输出: true

示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

进阶:
你能不将整数转为字符串来解决这个问题吗?

算法

动态规划递归

答案

/**
 * 动态规划
 */
var isPalindrome = function(x) {
    //#1 判断是否为负数
    if (x < 0) return false;

    //#2 取长度
    let num = 1;
    let count = 1;
    while (true) {
        num *= 10;
        if (num > x) break;
        count++;
    }
    
    return isChildPalind(x, count);
};

var isChildPalind = function(x, len) {
    //#1 单数直接返回
    if (len === 0 || len === 1) return true;

    //#2 取数
    const left_num = parseInt(x / Math.pow(10, len - 1));
    const right_num = x % 10;
    const child_num = (x - left_num * Math.pow(10, len - 1) - right_num) / 10;

    return left_num === right_num && isChildPalind(child_num, len - 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant