leetcode:Palindrome Number (判断数字是否回文串) 【面试算法题】
2013-09-30 21:46
363 查看
题目:
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.
题意判断数字是否是回文串,只能用常数空间,不能转换成字符串,不能反转数字。
先计算数字的位数,分别通过除法和取余,提取出要对比的对应数字。
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.
题意判断数字是否是回文串,只能用常数空间,不能转换成字符串,不能反转数字。
先计算数字的位数,分别通过除法和取余,提取出要对比的对应数字。
class Solution { public: bool isPalindrome(int x) { if(x<0)return 0; int n=0,temp=x,big=1,small=1; while(temp!=0) { n++; temp/=10; if(temp)big*=10; } for(int i=0;i<n/2;++i) { if((x/big)%10!=(x/small)%10)return 0; big/=10; small*=10; } return 1; } }; // http://blog.csdn.net/havenoidea[/code]
相关文章推荐
- leetcode:Palindrome Number (判断数字是否回文串) 【面试算法题】
- leetcode_9. Palindrome Number 判断一个整数是否是回文串数字
- Palindrome Number 判断一个数字是否是回文数字@LeetCode
- 【LeetCode008-009算法/编程练习C++】string转int(atoi),判断数字是否是回文
- 笔试面试算法经典--判断二叉树是否是平衡二叉树(Java)
- leetcode:Remove Duplicates from Sorted Array(去掉数组重复数字,常数空间限制)【面试算法题】
- 笔试算法题(29):判断元素范围1到N的数组是否有重复数字 & 计算整数的7倍
- 算法--判断一个数字序列是否为二叉排序树的后续遍历
- 【LeetCode-面试算法经典-Java实现】【136-Single Number(只出现一次的数字)】
- 经典算法面试题目-判断s2是否是s1的旋转字符串(1.8)
- 【LeetCode-面试算法经典-Java实现】【137-Single Number II(只字出一次的数字II)】
- C语言小算法集锦---判断输入的数字是否为回文数
- leetcode第9题,判断数字是否是回文数字的两种方法
- leetcode:Palindrome Partitioning (字符串分割成回文串的所有方式) 【面试算法题】
- LeetCode65——Valid Number(使用DFA)来判断字符串是否为数字
- 【LeetCode-面试算法经典-Java实现】【153-Find Minimum in Rotated Sorted Array(找旋转数组中的最小数字)】
- 【LeetCode-面试算法经典-Java实现】【129-Sum Root to Leaf Numbers(所有根到叶子结点组组成的数字相加)】
- leetcode——Palindrome Number 判断整数数字是否为回文(AC)
- 【LeetCode-面试算法经典-Java实现】【154-Find Minimum in Rotated Sorted Array II(找旋转数组中的最小数字II)】
- leetcode:Remove Duplicates from Sorted Array II (允许重复一次,去掉数组多余数字)【面试算法题】