[LeetCode]Palindrome Number解析

这道LeetCode题目要求判断一个整数是否为回文数,不允许使用额外空间。对于负数和可能的溢出情况,需要特殊处理。解决方法是通过不断取余和累加来检查数字的对称性。

链接https://leetcode.com/problems/palindrome-number/#/description
难度:Easy
题目:9.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.
翻译:确定一个整数是否是回文数。不能使用额外的空间。
一些提示:
负数能不能是回文数呢?(比如,-1)
如果你想将整数转换成字符串,但要注意限制使用额外的空间。
你也可以考虑翻转一个整数。
然而,如果你已经解决了问题"翻转整数",
那么你应该知道翻转的整数可能会造成溢出。
你将如何处理这种情况?
这是一个解决该问题更通用的方法。
思路:什么是回文?指的是“对称”的数,即将这个数的数字按相反的顺序重新排列后,所得到的数和原来的数一样。
这道题可以看成要计算一个数字是否是回文数字,我们其实就是将这个数字除以10,保留他的余数,下次将余数乘以10,加上这个数字再除以10的余数。依此类推,看能否得到原来的数。
注:负数不是回文数字,0是回文数字.
参考代码
Java

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0 || (x != 0 && x % 10 == 0)) return false;
        int r = 0;
        while (x > r) {
            r = r * 10 + x % 10;
            x = x /10;
        }
        return x == r || x == r / 10;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值