9. Palindrome Number LeetCode题解

来源:互联网 发布:数据库基础知识 编辑:程序博客网 时间:2024/06/06 00:39

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

click to show spoilers.

Subscribe to see which companies asked this question.

题意:

判断一个整数是否回文,不要使用额外空间;


题解:

此题最直观的解法应该是转成字符串再对比,这样就开辟了额外空间;

如果进行类似LeetCode 题8做的转换,可能越界(可以使用long类型);

一种比较好的思路是:设法获取整数的一半,并将整数的两部分进行对比是否一致(其中一部分进行翻转处理);


Code【Java】

public class Solution {    public boolean isPalindrome(int x) {        if (x == 0) return true;        if (x < 0 || (x % 10 == 0)) return false;        int half = 0;        for ( ; x > half; x /= 10) {            half = half * 10 + x % 10;        }        return (half == x) || (half / 10 == x);    }}

Code【C++】

class Solution {public:    bool isPalindrome(int x) {        if (x == 0) return true;        if (x < 0 || (x % 10 == 0)) return false;        int half = 0;        for ( ; x > half; x /= 10) {            half = half * 10 + x % 10;        }        return (half == x) || (half / 10 == x);    }};


0 0