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

9. Palindrome Number #205

Open
Tcdian opened this issue Jun 10, 2020 · 1 comment
Open

9. Palindrome Number #205

Tcdian opened this issue Jun 10, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jun 10, 2020

9. Palindrome Number

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

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

  • 你能不将整数转为字符串来解决这个问题吗?
@Tcdian Tcdian added the Math label Jun 10, 2020
@Tcdian
Copy link
Owner Author

Tcdian commented Jun 10, 2020

Solution

  • JavaScript Solution
/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    if (x === 0) {
        return true;
    }
    if (x < 0 || x % 10 === 0) {
        return false;
    }
    let reverseNum = 0;
    while(x > reverseNum) {
        reverseNum = reverseNum * 10 + x % 10;
        x = Math.floor(x / 10);
    }
    
    return x === reverseNum || x === Math.floor(reverseNum / 10);
};
  • TypeScript Solution
function isPalindrome(x: number): boolean {
    if (x === 0) {
        return true;
    }
    if (x < 0 || x % 10 === 0) {
        return false;
    }
    let reverseNum = 0;
    while(x > reverseNum) {
        reverseNum = reverseNum * 10 + x % 10;
        x = Math.floor(x / 10);
    }
    
    return x === reverseNum || x === Math.floor(reverseNum / 10);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant