博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 9 Palindrome Number 回文数
阅读量:4705 次
发布时间:2019-06-10

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

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.

非常简洁的c++解决方案:

对于回文数只比较一半

public boolean isPalindrome1(int x) {    if (x == 0) return true;    // in leetcode, negative numbers and numbers with ending zeros    // are not palindrome    if (x < 0 || x % 10 == 0)        return false;    // reverse half of the number    // the exit condition is y >= x    // so that overflow is avoided.    int y = 0;    while (y < x) {        y = y * 10 + (x % 10);        if (x == y)  // to check numbers with odd digits            return true;        x /= 10;    }    return x == y; // to check numbers with even digits}

python这个解法应该是前后分别对比:

class Solution:    # @param x, an integer    # @return a boolean    def isPalindrome(self, x):        if x < 0:            return False        ranger = 1        while x / ranger >= 10:            ranger *= 10        while x:            left = x / ranger            right = x % 10            if left != right:                return False            x = (x % ranger) / 10            ranger /= 100        return True

python字符串的解法:

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

转载于:https://www.cnblogs.com/wangyaning/p/7853955.html

你可能感兴趣的文章
mysql user表root 用户误删除解决方法
查看>>
servlet中参数的传递及如何防止出现中文乱码
查看>>
Hibernate分页
查看>>
SQLyog v11.24查询MySQL5.6.24中文乱码的解决方法
查看>>
顺序容器的insert使用方法
查看>>
彩色图像--图像增强 直方图增强
查看>>
IOS启动其他应用程序
查看>>
Hadoop-1.1.2、HBase-0.94.7完全分布式集群结构
查看>>
hdu 1698
查看>>
Session变量不能转移到下页.解决: session.use_trans_sid = 1
查看>>
CMap与hash_map效率对照
查看>>
为开发用途mac电脑瘦身
查看>>
Android中GridView的一些特殊属性
查看>>
DBUtils、QueryRunner的query/update/batch、ResultSetHandler的9个处理器、ThreadLocal管理conn进行事务处理的案例...
查看>>
如何调整DOS窗口的宽高
查看>>
简单邮箱验证(正则表达式)自学
查看>>
Markdown的使用
查看>>
有关JS的部分知识点
查看>>
Lotus Domino 代理 对表单域的常用操作
查看>>
Understanding the Bias-Variance Tradeoff
查看>>