leetcode——Palindrome Number 判断整数数字是否为回文(AC)
2014-06-08 09:38
344 查看
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.
这道题加了不能使用额外空间的限制,如果没有这个限制的话,我们大可以开辟一个字符串数组把整数的各位数字存储起来,然后使用指针进行判断。在这道题目的要求之下,我们只能每次把首尾的两个数字提取出来进行比较,然后再把这两个数字从原数字钟剔除,继续比较。。。直到所有数字比完,就可得出是回文的结论。个位数提取只需对10取余即可,最高位提取需要将原数字除以10^n次方即可。还有需要注意的是题目要求负数不存在回文。code如下:
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
int base = 1;
int temp = x;
while((temp=temp/10) != 0)
base *= 10;
temp = x;
while(temp != 0)
{
if(temp%10 == temp/base)
{
temp = (temp - temp/base*base)/10;
base /= 100;
}
else
{
return false;
}
}
return true;
}
};
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.
这道题加了不能使用额外空间的限制,如果没有这个限制的话,我们大可以开辟一个字符串数组把整数的各位数字存储起来,然后使用指针进行判断。在这道题目的要求之下,我们只能每次把首尾的两个数字提取出来进行比较,然后再把这两个数字从原数字钟剔除,继续比较。。。直到所有数字比完,就可得出是回文的结论。个位数提取只需对10取余即可,最高位提取需要将原数字除以10^n次方即可。还有需要注意的是题目要求负数不存在回文。code如下:
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
int base = 1;
int temp = x;
while((temp=temp/10) != 0)
base *= 10;
temp = x;
while(temp != 0)
{
if(temp%10 == temp/base)
{
temp = (temp - temp/base*base)/10;
base /= 100;
}
else
{
return false;
}
}
return true;
}
};
相关文章推荐
- 【LeetCode008-009算法/编程练习C++】string转int(atoi),判断数字是否是回文
- LeetCode--判断一个十进制数字是否为回文
- leetcode_9. Palindrome Number 判断一个整数是否是回文串数字
- java 编写程序实现从控制台接收一个 5 位以上的整数,使用数组来判断该数字 * 是否是回文数。(例如:789987,12344321是回文数)
- leetcode第9题,判断数字是否是回文数字的两种方法
- Palindrome Number 判断一个数字是否是回文数字@LeetCode
- Palindrome Number leetcode 判断一个整数是否是回文
- Leetcode练习<十二> 判断整数是否为回文
- leetcode 9 给一个int类型的数字,判断是否是回文数
- 【华为面试题】给定一个数字(整数),判断它是否回文
- leetcode之O(1)空间复杂度判断一个整数是否是回文整数
- leetcode Palindrome Number (判断整数是否为回文)
- JS判断是否为数字,是否为整数,是否为浮点数
- js判断输入是否为正整数、浮点数等数字的函数代码
- js判断输入是否为正整数、浮点数等数字的函数
- js如何判断输入是否为正整数、浮点数等数字的函数
- JS判断是否为数字,是否为整数,是否为浮点数
- js如何判断输入是否为正整数、浮点数等数字的函数
- js判断是否为数字, 是否为整数, 是否为浮点数
- js判断输入是否为正整数、浮点数等数字的函数