LeetCode Palindrome Number(009)解法总结

314 阅读1分钟

描述

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?

思路

对于这种简单的逆序问题,将输入转化为StringBuffer对象,再调用逆置函数即可。

但是题目要求不能转换为字符串,所以要从整型下手。

  1. 当数字为负数时,是肯定不满足要求的。
  2. 当数字为正数或0时,只要保证每位数字从高到低的权重*数字之和,等于每位数字从低到高的权重*数字之和,说明这个正数是对称的。
class Solution {
    public boolean isPalindrome(int x) {
        boolean flag = true;
        if(x < 0){
            flag = false;
        }
        
        //数字逆置过程
        int temp = x, out = 0;
        while(temp != 0){
            out = out * 10 + temp % 10;
            temp = temp / 10;
        }
        
        if(x != out){
            flag = false;
        }
        
        return flag;
    }
}
Runtime: 7 ms, faster than 80.18% of Java online submissions for Palindrome Number.
Memory Usage: 40.5 MB, less than 5.02% of Java online submissions for Palindrome Number.