标签:
Determine whether an integer is a palindrome. Do this without extra space.
解题分析:
题目很简单,但是对于要求需要看清楚。
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.
1,负数都不是回文数;
2,不能通过将数字转为字符串来判断回文,因为使用了额外的空间(即只能使用空间复杂度 O(1) 的方法);
3,注意整数溢出问题;
4,这个问题有一个比较通用的解法。
Subscribe to see which companies asked this question
解题方法就是利用数学方法,将最后一位变为第一位,分别乘以10,然后依次升位。
# -*- coding:utf-8 -*- __author__ = 'jiuzhang' class Solution(object): def isPalindrome(self, x): if x < 0 or (x != 0 and x % 10 == 0): return False y = 0 while x > y: y = y * 10 + x % 10 x /= 10 return x == y or y / 10 == x
(LeetCode)Palindrome Number -- 判断回文数
标签:
原文地址:http://blog.csdn.net/u012965373/article/details/52160370