[LeetCode]Palindrome Number解析

链接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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容