PalindromeNumber

Determine whether an integer is a palindrome. 
An integer is a palindrome when it reads the same backward as forward.
查看整形数字是否是回文,例如121
public class PalindromeNumber {

    //思路,可以弄成char数组
    public static boolean isPalindromeNumber(int x){
        String a = x+"";
        String b = "";
        int j=0;
        char[] reverse=null;
        for (int i=a.length()-1;i>=0;i--){
           char item = a.charAt(i);
           reverse[j] = item;
           j++;
        }
        if (a.equals(reverse.toString())){
            return true;
        }else{
            return false;
        }
    }

    public static void main(String[] args) {
        isPalindromeNumber(121);
    }
}

报错了,空指针异常。

Exception in thread "main" java.lang.NullPointerException
    at com.coder520.jxc.leetcode.PalindromeNumber.isPalindromeNumber(PalindromeNumber.java:20)
    at com.coder520.jxc.leetcode.PalindromeNumber.main(PalindromeNumber.java:31)

 这是弄成字符串,莫有难度

public class PalindromeNumber {

    //思路,可以弄成char数组
    public static boolean isPalindromeNumber(int x){
        if (x<0){
            return false;
        }
        String str_x = x+"";
        char[] s = str_x.toCharArray();
        int left = 0,right = str_x.length()-1;
        while (left<right){
            //判断相等,不相等返回false,哈哈
            if (s[right] != s[left]){
                return false;
            }else {
                left++;
                right--;
            }
        }
        return true;
    }

    public static void main(String[] args){
        System.out.println(isPalindromeNumber(121));
    }

}

 

 
posted @ 2018-12-20 00:24  正能量教官  阅读(162)  评论(0编辑  收藏  举报