首页 > 其他 > 详细

Leetcode: Palindrome Number

时间:2015-03-22 15:05:10      阅读:277      评论:0      收藏:0      [点我收藏+]

题目:
Determine whether an integer is a palindrome. Do this without extra space.

思路分析:
回文判断,题目提示不能使用直接转字符串,不能翻转数字。
那只能一个一个取出数字进行比较了。

C++参考代码:

class Solution
{
public:
    bool isPalindrome(int x)
    {
        if (x < 0) return false;
        if (x == 0) return true;

        int scale = 1;//标记x的数量级
        while (x / scale >= 10)
        {
            scale *= 10;
        }
        int left, right;
        while (x)
        {
            left = x / scale;//最最左边的数字
            right = x % 10;//最右边的数字
            if (left != right) return false;

            x -= left * scale;//去掉最左边的数字
            x /= 10;//去掉最右边的数字
            scale /= 100;//x的数量级较少两级
        }
        return true;
    }
};

C#参考代码:

public class Solution
{
    public Boolean IsPalindrome(int x)
    {
        if (x < 0) return false;
        if (x == 0) return true;

        int scale = 1;
        while (x / scale >= 10)
        {
            scale *= 10;
        }

        int left = 0;
        int right = 0;
        while (x != 0)
        {
            left = x / scale;
            right = x % 10;
            if (left != right) return false;

            x -= left * scale;
            x /= 10;
            scale /= 100;
        }
        return true;
    }
}

Python参考代码:
如果使用Python3.x,请将其中的一般除法/换成floor除法//(两个/表示floor除法)

class Solution:
    # @return a boolean
    def isPalindrome(self, x):
        if x < 0:
            return False
        if x == 0:
            return True

        scale = 1
        while x / scale >= 10:
            scale = scale * 10

        while x != 0:
            left = x / scale
            right = x % 10
            if left != right:
                return False
            x = x - left * scale
            x = x / 10
            scale = scale / 100
        return True

Leetcode: Palindrome Number

原文:http://blog.csdn.net/theonegis/article/details/44537593

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!