Loading

回文数

回文数

题目:https://leetcode-cn.com/problems/palindrome-number/description/

package com.test;

public class Lesson003 {
    public static void main(String[] args) {
        int i = 121;
        boolean isHuiwen = judgeHuiwen(i);
        System.out.println(isHuiwen);
    }

    private static boolean judgeHuiwen(int x) {
        // 负数不回文
        if (x < 0) {
            return false;
        }
        // 10以内回文,0也是回文
        if (x < 10) {
            return true;
        }
        // 末尾是0不回文
        if ((x ^ 0) == 0) {
            return false;
        }
        // 最多10位数
        int[] arr = new int[10];
        int index = 0;
        while (true) {
            int i1 = x % 10;
            arr[index] = i1;
            index++;
            x = x / 10;
            if (x < 10) {
                break;
            }
        }
        arr[index] = x;
        for (int j = 0; j <= index; j++) {
            // 首尾不相等就返回false
            if (arr[j] - arr[index - j] != 0) {
                return false;
            }
            // 到了中心点就返回true
            if (j >= index / 2) {
                return true;
            }
        }
        return true;
    }
}

 

posted @ 2018-08-10 22:03  stono  阅读(125)  评论(0编辑  收藏  举报