坚持写

LeetCode 解题报告 - 9. Palindrome Nu

2016-10-13  本文已影响0人  秋名山菜车手

编程语言是 Java,代码托管在我的 GitHub 上,包括测试用例。欢迎各种批评指正!

<br />

题目 —— Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.

<br >

解答

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0 || x != 0 && x % 10 == 0) {
            return false;
        }
        int reverse = 0;
        while (reverse < x) {
            reverse = reverse * 10 + x % 10;
            x = x / 10;
        }
        return (x == reverse) || (x == reverse/10);
    }
}
上一篇下一篇

猜你喜欢

热点阅读