博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode刷题9 回文数 Palindrome Number(简单) Python Java
阅读量:4129 次
发布时间:2019-05-25

本文共 1421 字,大约阅读时间需要 4 分钟。

题目描述:

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例1:

输入: 121

输出: true

示例2:

输入: -121

输出:假
解释:从左向右读,为-121。从右向左读,为121-。因此它不是一个回文数。

示例3:

输入: 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/

你可能感兴趣的文章
单例模式
查看>>
工厂方法模式
查看>>
模板方法模式
查看>>
数据结构之队列、栈
查看>>
数据结构之树
查看>>
数据结构之二叉树
查看>>
二叉树非递归遍历算法思悟
查看>>
红黑树算法思悟
查看>>
从山寨Spring中学习Spring IOC原理-自动装配注解
查看>>
实例区别BeanFactory和FactoryBean
查看>>
Spring后置处理器BeanPostProcessor的应用
查看>>
Spring框架的ImportSelector到底可以干嘛
查看>>
Mysql中下划线问题
查看>>
微信小程序中使用npm过程中提示:npm WARN saveError ENOENT: no such file or directory
查看>>
Xcode 11 报错,提示libstdc++.6 缺失,解决方案
查看>>
idea的安装以及简单使用
查看>>
Windows mysql 安装
查看>>
python循环语句与C语言的区别
查看>>
Vue项目中使用img图片和background背景图的使用方法
查看>>
vue 项目中图片选择路径位置static 或 assets区别
查看>>