码迷,mamicode.com
首页 > 其他好文 > 详细

(LeetCode)Palindrome Number -- 判断回文数

时间:2016-08-09 10:48:00      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

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.

1,负数都不是回文数;

2,不能通过将数字转为字符串来判断回文,因为使用了额外的空间(即只能使用空间复杂度 O(1) 的方法);

3,注意整数溢出问题;

4,这个问题有一个比较通用的解法。

Subscribe to see which companies asked this question

难度不大,只需要加判断就可以了。此处结尾是0的数不是回文数。

解题方法就是利用数学方法,将最后一位变为第一位,分别乘以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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!