LeetCode习题笔记——判断数字是否回文
2017-12-28 18:53
169 查看
直接上题:
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
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。
这个题最大的要求就是不能用额外空间,即不可以将数字转为字符串然后再用判断字符串回文的方式。然而还是比较简单的:class Solution {
public:
bool isPalindrome(int x) {
int a = x, r = 0;
if (x < 0) return false;
while (a > 0) {
r = r*10 + a%10;
a = a / 10;
}
return r == x;
}
};
相当于一直将数字第一个数位作为比较数的末尾,最后看得到的数字是否相同即可。
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
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。
这个题最大的要求就是不能用额外空间,即不可以将数字转为字符串然后再用判断字符串回文的方式。然而还是比较简单的:class Solution {
public:
bool isPalindrome(int x) {
int a = x, r = 0;
if (x < 0) return false;
while (a > 0) {
r = r*10 + a%10;
a = a / 10;
}
return r == x;
}
};
相当于一直将数字第一个数位作为比较数的末尾,最后看得到的数字是否相同即可。
相关文章推荐
- 判断数字是否是回文
- leetcode——Palindrome Number 判断整数数字是否为回文(AC)
- python键盘输入五个数字,判断是否是回文数
- python判断一个数是否为回文数字
- leetcode palindrome-number(判断一个数字是否是回文)
- 【华为面试题】给定一个数字(整数),判断它是否回文
- 第十一周项目3-6-判断一个数字是否回文
- 判断一串数字是否回文
- 编写一个Java应用程序。用户从键盘输入一个1—9999之间的数,程序将判断这个数是几位数, 并判断这个数是否是回文数。回文数是指将该数含有的数字逆序排列后得到的数和原数相同, 例如12121、3
- 判断整型数字是否是回文
- 判断是否是回文数字
- valid-palindrome——判断带符号数字字母的字符串是否为回文
- 作业 4 函数应用 编写一个程序,判断从键盘接收的数字是否为回文数字。回文数字就是顺着看和倒着看是相同的数。如121、656、2332等
- 判断数字是否是回文数字(无需另外开销)
- 9. Palindrome Number(判断整型数字是否是回文,直接暴力即可)
- C语言小算法集锦---判断输入的数字是否为回文数
- 判断一个数字是否是回文
- Lettcode_9_Palindrome Number ——判断一个数字是否回文(不能申请额外空间)
- 判断一个数字是否回文数字
- 判断是否是回文数字(java版)