LeetCode笔记:(Java) 9. Palindrome Number

来源:互联网 发布:同和行知职业技术学校 编辑:程序博客网 时间:2024/06/08 06:50

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)

原创粉丝点击