Palindrome Number
2015-06-13 11:15
393 查看
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.
方法一(不推荐):利用Reverse Integer的方法,求的转换后的数字,然后比较是否相等。提示说这样有溢出的问题,想了想感觉问题不大。因为首先输入必须是一个合法的int值,负数直接返回false,对于正数,假设输入的int是一个palindrome,reverse之后依然不会溢出,所以正常返回true;所以如果转换后溢出了,证明肯定不是palindrome,溢出后的数字跟输入一般不相同(想不出相等的情况-_-!,求指点),所以返回了false。
方法二:从两头依次取数字比较,向中间推进。
C代码如下:
小结:
(1)注意所有可能发生的变量溢出的情况,如果第一个for循环里的终止条件是x/base != 0,则x足够大时base可能溢出。
(2)如果需要一直用到10的次方这样的数,可以一开始就算出来并保存在变量里,而不必每次都调用pow()函数,减少计算量。
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.
方法一(不推荐):利用Reverse Integer的方法,求的转换后的数字,然后比较是否相等。提示说这样有溢出的问题,想了想感觉问题不大。因为首先输入必须是一个合法的int值,负数直接返回false,对于正数,假设输入的int是一个palindrome,reverse之后依然不会溢出,所以正常返回true;所以如果转换后溢出了,证明肯定不是palindrome,溢出后的数字跟输入一般不相同(想不出相等的情况-_-!,求指点),所以返回了false。
方法二:从两头依次取数字比较,向中间推进。
C代码如下:
bool isPalindrome(int x) { int i, j; if(x < 0) return 0; else if(x < 10) return 1; int base = 1; int save; save = x; for(i = 0; x / base >= 10 ; i++) base *= 10; for(j = 0; i >= j; j++) { if(save / base != x % 10) return 0; else { save %= base; x /= 10; base /= 10; i--; } } return 1; }
小结:
(1)注意所有可能发生的变量溢出的情况,如果第一个for循环里的终止条件是x/base != 0,则x足够大时base可能溢出。
(2)如果需要一直用到10的次方这样的数,可以一开始就算出来并保存在变量里,而不必每次都调用pow()函数,减少计算量。
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)