LeetCode 9 Palindrome Number

本文介绍了如何不使用额外空间来判断整数是否为回文数,并提供了多种编程语言实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值