leetcode9.回文数(数值反转)

public class LeetCode9 {

//回文数判断方法
public boolean huiwen(int num){
//存放回文数
int rec=num,newRec=0;
//负数和个位为零的数不可能是回文数
//修改,0是回文数,所以需判断num是不是等于0
if(num<0||num%10==0&&num!=0){
return false;
}
/**
* 方法类似于数据反转(参考leetcode7
* while循环rec>newRec原因是只需要转换一半即可判断是否属于回文数
* 当数据为双位时可直接判断,为单位时中位数不变不影响结果,可去掉中位数进行判断
*/
while (rec>newRec){
newRec=newRec*10+rec%10;
rec/=10;
}
return rec==newRec||rec==newRec/10;
}

public static void main(String args[]){
Scanner sc=new Scanner(System.in);
LeetCode9 leedCode9=new LeetCode9();
System.out.println("请输入你要进行判断的数据是不是回文数:");
int num=sc.nextInt();
System.out.println(leedCode9.huiwen(num));
}

}

/**leetcode提交代码
*class Solution {
* public boolean isPalindrome(int x) {
* //存放回文数
* int rec=x,newRec=0;
* //负数和个位为零的数不可能是回文数
* if(x<0||x%10==0&&x!=0){
* return false;
* }
*
* //方法类似于数据反转(参考leetcode7
* //while循环rec>newRec原因是只需要转换一半即可判断是否属于回文数
* //当数据为双位时可直接判断,为单位时中位数不变不影响结果,可去掉中位数进行判断
while (rec>newRec){
newRec=newRec*10+rec%10;
rec/=10;
}
return rec==newRec||rec==newRec/10;
}
}
*/

猜你喜欢

转载自www.cnblogs.com/shudaixiongbokeyuan/p/13368965.html