LeetCode题解:Palindrome Number

来源:互联网 发布:护肤品成分查询软件 编辑:程序博客网 时间:2024/05/16 12:57

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

click to show spoilers.

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?

题意:判断一个数是否为回文

解题思路:将它从个位向高位转换为一个数,如果转换后的数和之前的数相等,就是回文数。但是转换可能会溢出,所以用long会好一点

代码:

public class Solution {    public boolean isPalindrome(int x) {        int palindrome = 0;        int input = x;        if(x < 0){            return false;        }        while(input != 0){            palindrome = palindrome * 10 + input % 10;            input = input / 10;        }        return palindrome == x;    }}
0 0
原创粉丝点击