[LeetCode] 009. Palindrome Number (Easy) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode


009.Palindrome_Number (Easy)

链接

题目:https://oj.leetcode.com/problems/palindrome-number/
代码(github):https://github.com/illuz/leetcode

题意

判断一个数是否是回文数。

分析

按自己想的去写就行了。

  1. 可以先转为字符串,再判断。(这种解法用 Python 可以一句话完成 =w=)
  2. 更好的方法是直接算出回文的数再直接比较。

代码

C++:(可以先转为字符串)

class Solution {
public:
    bool isPalindrome(int x) {
		if (x < 0) return false;
		int bit[10];
		int cnt = 0;
		while (x) {
			bit[cnt++] = x % 10;
			x /= 10;
		}
		for (int i = 0; i < cnt; i++)
			if (bit[i] != bit[cnt - i - 1])
				return false;
		return true;
    }
};


Python:

class Solution:
    # @return a boolean
    def isPalindrome(self, x):
        return str(x) == str(x)[::-1]


C++:(算出回文)

class Solution {
public:
    bool isPalindrome(int x) {
		long long xx = x;
		long long new_xx = 0;

		while (xx > 0) {
			new_xx = new_xx * 10 + xx % 10;
			xx /= 10;
		}

		return new_xx == (long long)x;
    }
};


Java:

public class Solution {

    public boolean isPalindrome(int x) {
        long xx = x;
        long new_xx = 0;
        while (xx > 0) {
            new_xx = new_xx * 10 + xx % 10;
            xx /= 10;
        }
        return new_xx == x;
    }
}


Python:

class Solution:
    # @return a boolean
    def isPalindrome(self, x):
        xx = x
        new_xx = 0
        while xx > 0:
            new_xx = new_xx * 10 + xx % 10
            xx /= 10

        return new_xx == x


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值