My java solution for Palindrome Number


  • 0
    P
    public class Solution {
        //输入的数可能是负数
        //注意不要越界
        public boolean isPalindrome(int x) {
            if(x < 0) {
                return false;
            }
            if(x == 0) {
                return true;
            }
            //计算出数组是几位数
            int count = 1;
            int temp = x;
            while(temp >= 10) {
                temp = temp / 10;
                count ++;
            }
            //每次从头和尾对应取数字比较
            temp = x;
            int divisor = (int)Math.pow(10, count - 1);
            //将每位数字放在一个数组中
            int[] numArray = new int[count];
            for(int i = 0; i < count; i++) {
                numArray[i] =  temp / divisor;
                temp %= divisor;
                divisor /= 10;
            }
            //从数组的头和尾对应向中间方向比较
            int high = count - 1;
            int low = 0;
            while(low < high) {
                if(numArray[low] != numArray[high]) {
                    return false;
                }
                low ++;
                high --;
            }
            return true;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.