LeetCode笔记:(Java) 9. Palindrome Number

Question:

Determine whether an integer is a palindrome. Do this without extra space.

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.

My Solution:

(Runtime only beats 5.21 % of java submissions.)

class Solution {
    public boolean isPalindrome(int x) {
//      if(x < 0) {     //负数不能是回文
//          return false;
//      }
        String xToString = Integer.toString(x);
        int length = xToString.length();
        int mid = length / 2;   //长度中间值
        int count = 0;      //相等的位置对数
        for (int position = 0; position < mid; position++) {
            if (xToString.charAt(position) == xToString.charAt(length - 1 - position)) {      //若当前头尾相同
                count++;
            }
        }

        if (count == mid) {
            return true;
        } else {
            return false;
        }
    }
}
思路:

先将输入的数值转为String类型(性能较差),再从字符串头尾分别出发,判断对应的字符是否一致,直至比较到字符串的中部。若相等的字符对数与字符串中值的index(即mid)相等,则为回文数。
(若输入负数,如"-121",会分解成'-' '1' '2' '1'判断,故一定不会是回文)

Other People’s Solution:

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);
}
理解:
  1. 先排除 x为负数 或 x为0结尾的非零数字 这两种情况。
  2. x从后往前,将每一位的值存放到rev中,直至revx相差1位(原始数字位为奇数)或0位(原始数字位为奇数)
  3. 比较xrev的值是否相等(原始数字位为奇数时需要使用x == rev / 10去掉最中间一位)

摘自 —— https://discuss.leetcode.com/topic/8090/9-line-accepted-java-code-without-the-need-of-handling-overflow (作者:cbmbbz)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值