[LeetCode]Palindrome Number解析

简介: 链接:https://leetcode.com/problems/palindrome-number/#/description难度:Easy题目:9.Palindrome NumberDetermine whether an integer is a palindrome.

链接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;
    }
}
目录
相关文章
|
4月前
|
算法 vr&ar 图形学
☆打卡算法☆LeetCode 220. 存在重复元素 III 算法解析
☆打卡算法☆LeetCode 220. 存在重复元素 III 算法解析
|
5月前
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
64 1
|
3月前
|
SQL Python
力扣刷MySQL-第二弹(详细解析)
力扣刷MySQL-第二弹(详细解析)
|
3月前
|
开发框架 关系型数据库 MySQL
力扣刷MySQL-第一弹(详细解析)
力扣刷MySQL-第一弹(详细解析)
|
9月前
|
存储 算法 C++
(C语言版)力扣(LeetCode)题库1-5题解析
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
|
4月前
|
算法 vr&ar 图形学
☆打卡算法☆LeetCode 202. 快乐数 算法解析
☆打卡算法☆LeetCode 202. 快乐数 算法解析
|
4月前
|
算法 Java vr&ar
☆打卡算法☆LeetCode 179. 最大数 算法解析
☆打卡算法☆LeetCode 179. 最大数 算法解析
|
4月前
|
SQL 算法 vr&ar
☆打卡算法☆LeetCode 178. 分数排名 算法解析
☆打卡算法☆LeetCode 178. 分数排名 算法解析
|
4月前
|
SQL 算法 vr&ar
☆打卡算法☆LeetCode 177. 第N高的薪水 算法解析
☆打卡算法☆LeetCode 177. 第N高的薪水 算法解析
|
4月前
|
SQL 算法 vr&ar
☆打卡算法☆LeetCode 176. 第二高的薪水 算法解析
☆打卡算法☆LeetCode 176. 第二高的薪水 算法解析

推荐镜像

更多