判断一个数是不是回文数
我的想法是先将数字变成数组,然后设置两个指针分别从开头和末尾一一比对.
话不多说,代码如下:
package com.yangshunfan.LintCode;
/*
* 判断一个数是不是回文数
*/
public class HuiWenShu {
public static boolean palindromeNumber(int num) {
boolean b = true;
/*
* 先将数字变为数组
*/
String s = num + "";
int[] nums = new int[s.length()];
for (int i = 0; i < nums.length; i++) {
char c = s.charAt(i);
nums[i] = Character.getNumericValue(c);
}
//设置两个指针
int left = 0;
int right = nums.length - 1;
if(nums.length > 1){
while(right >= left){
if(nums[left] == nums[right] && left < nums.length - 1 && right >= 0){
left++;
right--;
} else {
b = false;
break;
}
}
}else if(nums.length == 1){
b = true;
}
return b;
}
public static void main(String[] args) {
int n = 12344321;
System.out.println(palindromeNumber(n));
//palindromeNumber(n);
}
}