本文共 1421 字,大约阅读时间需要 4 分钟。
题目描述:
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例1:
示例2:输入: 121
输出: true
示例3:输入: -121
输出:假 解释:从左向右读,为-121。从右向左读,为121-。因此它不是一个回文数。
输入: 10
输出: false 解释:从右向左读,为01。因此它不是一个回文数。
第一种方法,很简单,通过字符串来判断
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ return str(x) == str(x)[::-1]if __name__ == '__main__': s = Solution() a = s.isPalindrome(-121) print(a)
第二种方法,不将整数转为字符串来解决这个问题
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ tmp = x # 定义一个变量存储x的临时变量 result = 0 # 定义一个变量存储x倒序后的值 # 当tmp大于0的时候循环,这里筛选负数 while tmp > 0: # result*10加上result和10取余的数 result = result * 10 + (tmp % 10) # tmp整除10 tmp = tmp // 10 return result == xif __name__ == '__main__': s = Solution() a = s.isPalindrome(-121) print(a)
在pyhon3中/ 是真除法: 3/2=1.5
地板除是//,是取整数位: 3//2=1
% 表示求余数: 5%2=1
以下是Java版本:
首先,负数不是回文数字,其次对数字进行逆转,123变成321这样,如果变换后的数字相等说明是回文数字。
public class PalindromeNumber { public boolean isPalindrome(int x) { if (x < 0) { // 负数不是回访数字 return false; } long reverse = 0; // 数字逆转后的值,为了不使用溢出采用long int tmp = x; while (tmp != 0) { // 求逆转后的值 reverse = reverse * 10 + tmp % 10; tmp /= 10; } return x == reverse; // 判断是否是回文数字 }}
转载地址:http://wsuvi.baihongyu.com/