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

LeetCode 9 Palindrome Number

时间:2015-05-07 12:28:14      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c   c++   java   python   

Problem:

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

click to show spoilers.

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.

Solution:

转化为字符串处理,查看是否回文

题目大意:

给定一个整数,返回这个数字是否是回文数。

解题思路:

直接转化为字符串判断,不过要明确回文数字的定义:负数不为回文数,前置零不算,比如01210不是回文数。

Java源代码(用时454ms):

public class Solution {
    public boolean isPalindrome(int x) {
        if(x<0)return false;
        int[] str = new int[11];
        int index=0;
        while(x>0){
            str[index++]=x%10;
            x/=10;
        }
        int i=0,j=index-1;
        while(i<j){
            if(str[i]!=str[j])return false;
            i++;j--;
        }
        return true;
    }
}


C语言源代码(用时153ms):

bool isPalindrome(int x) {
    int i,j,index=0;
    char str[12];
    if(x<0)return false;
    while(x>0){
        str[index++]=x%10+'0';
        x=x/10;
    }
    i=0;j=index-1;
    while(i<j){
        if(str[i]!=str[j])return false;
        i++;j--;
    }
    return true;
}


C++源代码(用时122ms):

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0)return false;
        char str[11];
        int index=0;
        while(x>0){
            str[index++]=x%10;
            x/=10;
        }
        int i=0,j=index-1;
        while(i<j){
            if(str[i]!=str[j])return false;
            i++;j--;
        }
        return true;
    }
};


Python源代码(用时53ms):

class Solution:
    # @param {integer} x
    # @return {boolean}
    def isPalindrome(self, x):
        if x<0:return False
        str=[]
        while x>0:
            str.append(x%10)
            x/=10
        i=0;j=len(str)-1
        while i<j:
            if str[i]!=str[j]:return False
            i+=1;j-=1;
        return True


LeetCode 9 Palindrome Number

标签:leetcode   c   c++   java   python   

原文地址:http://blog.csdn.net/runningtortoises/article/details/45558385

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