Palindrome Number

问题定义

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

判断一个数值反转之后是否还一样,包括符号在内要判断。

我的思路

这不和之前写的回文有点类似吗?所以我就先按回文的思路将数据进行逆向转换,可参考上一篇文章“Reverse Integer”

链接:https://blog.csdn.net/weixin_41775937/article/details/80304308

因为连符号都要判断,因此在两数相减时,我加上了绝对值,那么若是负数,即使转换后数值相等,但是相减也不为0啦。

开始这么写本来就有点懒惰的感觉,后面就想将integer类转换成string类进行回文判断,但是发现提示里面要求不要转成string类,大家知道还有这个方法就好啦。

代码

class Solution {
    public boolean isPalindrome(int x) {
        int reverse=0;
        int xyuan=x;
        while(x!=0){
            reverse=reverse*10+x%10;
            x=x/10;
        }
        return (Math.abs(reverse)-xyuan==0);
    }
}

学习别人的代码

因为我自己的代码思路还是不行啊,效率低,但是我可以不断学习,让我们来学习一个名为cbmbbz的码友。

compare half of the digits in x, so don't need to deal with overflow.

public boolean isPalindrome(int x) {
    if (x<0 || (x!=0 && x%10==0)) return false;
    int rev = 0;
    while (x>rev){
    	rev = rev*10 + x%10;
    	x = x/10;
    }
    return (x==rev || x==rev/10);
}
emmmmmm...好像差不多吼~不过因为他的判断,想法就比我写的多了,他的代码不用考虑溢出问题。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值