【Leet Code】Palindrome Number
2014-08-27 00:55
183 查看
Palindrome Number
Total Accepted: 19369 TotalSubmissions: 66673My Submissions
Determine whether an integer is a palindrome. Do this without extra space.
判断一个数整数是不是回文?例如121,1221就是回文,好吧,直接利用前面写过的【Leet
Code】Reverse Integer——“%”你真的懂吗?
不过这里要考虑翻转后,数值溢出的问题,代码如下:
/* //first method class Solution { public: bool isPalindrome(int x) { long long temp = x; long long ret = 0; bool isNegative = false; if (temp < 0) { return false; } while (temp) { ret = ret * 10 + temp % 10; temp /= 10; } if(x == ret) { return true; } else { return false; } } }; */
当然,我们还有更好的方法,其实,初见这个题目,第一个想法是取头取尾进行比较,然后把头尾去掉,再循环,直到数值为个位数为止:
class Solution { public: bool isPalindrome(int x) { if (x < 0) { return false; } int divisor = 1; while (x / divisor >= 10) { divisor *= 10; } while (x) { if (x / divisor != x % 10) { return false; } x = (x % divisor) / 10; divisor /= 100; } return true; } };
相关文章推荐
- [Leet Code] Reverse String(Java)
- Leet Code 7 Reverse Integer
- [leet code] Reverse Integer
- [leet code] Balanced Binary Tree
- [leet code] Minimum Path Sum
- [leet code] Spiral Matrix II
- [leet code] Unique Paths II
- Leet code —Jump Game
- [leet code] Partition List
- [leet code] Insertion Sort List
- [leet code] Construct Binary Tree from Inorder and Postorder Traversal
- Leet Code 12 Integer to Roman - 整数转成罗马数字 - Java
- Leet Code 24 Swap Nodes in Pairs - 成对交换节点 - Java
- 【Leet Code】81. Search in Rotated Sorted Array II---Medium
- 【Leet Code】74. Search a 2D Matrix---Medium
- Leet Code 42 Trapping Rain Water - Java
- Leet Code 65 Valid Number - 有效的数字 - Java
- Leet Code 70 Climbing Stairs - 爬楼梯 - Java
- 【Leet Code】Reverse Integer——“%”你真的懂吗?
- leet code. 15. 3Sum (暴力???)