回文数

问题

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:
输入: 121 输出: true

示例 2:
输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:
输入: 10 输出: false 解释: 从右向左读, 为 01 。
因此它不是一个回文数。

思路

思路很简单明了嘛,回文数,颠倒以后还一样的数字,那你就颠倒一下嘛。不过有几种情况可以直接判定。

  1. 负数。因为符号颠倒过来以后负号在后面,那肯定就不是个数字嘛,直接排除。
  2. 个位数是0的数字。这肯定也不行嘛,因为颠倒以后0在最高位,你见过最高位是0的整数吗?没有,所以排除掉。至于说颠倒整数嘛,可以参考我前面写过的颠倒整数

使用

package com.company;

public class Main {

    public static void main(String[] args) {
    // write your code here
        System.out.println(Solution.isPalindrome(10));
    }
}

输出

这不是回文数
false

Process finished with exit code 0

实现

package com.company;

public class Solution {
    /**
     * 判断一个数是不是回文数
     * @param inputInt
     * @return
     */
    static public boolean isPalindrome(int inputInt) {
        if (inputInt < 0 || (inputInt > 0 && inputInt % 10 == 0)) {
            System.out.println("这不是回文数");
            return false;
        }
        if (inputInt == 0)
            return true;
        int reveredInt = Solution.reverseInt(inputInt);
        if (reveredInt == 0)return false;
        else {
            if (inputInt - reveredInt == 0)return true;
            else return false;
        }
    }

    static private int reverseInt(int inputInt) {
        if (inputInt > Integer.MAX_VALUE || inputInt < Integer.MIN_VALUE) {
            System.out.println("输入数字越界");
            return 0;
        }
        int pseudoMax = Integer.MAX_VALUE / 10;
        int maxLowestNumber = Integer.MAX_VALUE % 10;
        int minLowestNumber = Integer.MIN_VALUE % 10;
        int inputCopy = inputInt;
        int result = 0;
        while (inputCopy != 0) {
            int singleNumber = inputCopy % 10;
            inputCopy /= 10;
            if (Math.abs(result) > pseudoMax) {
                return 0;
            } else if (Math.abs(result) == pseudoMax) {
                result *= 10;
                if (inputInt < 0) {
                    if (singleNumber < minLowestNumber)return 0;
                    else result += singleNumber;
                } else {
                    if (singleNumber > maxLowestNumber)return 0;
                    else result += singleNumber;
                }
            } else {
                result = result * 10 + singleNumber;
            }
        }
        return result;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容