前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[LeetCode]Palindrome Number回文

[LeetCode]Palindrome Number回文

作者头像
尾尾部落
发布2018-09-04 13:13:38
5670
发布2018-09-04 13:13:38
举报
文章被收录于专栏:尾尾部落尾尾部落

链接https://leetcode.com/problems/palindrome-number/#/description

难度:Easy

题目: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是回文数字.

参考代码

代码语言:javascript
复制
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;
    }
}

版权属于: 尾尾部落

原文地址: https://cloud.tencent.com/developer/article/1327467

转载时必须以链接形式注明原始出处及本声明。

window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"1","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')0||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档