您的位置:首页 > 编程语言 > Java开发

leetcode:Palindrome Number 【Java】

2016-03-05 11:18 465 查看
一、问题描述

Determine whether an integer is a palindrome. Do this without extra space.

二、问题分析

1、分别获取该数的最高位和最低位数字,比较是否一致。

2、当为负数时,返回false。

三、算法代码

public class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0){//当x为负数时,返回false
			return false;
		}
		int order = 1;//用于获取x的阶,例如x=1221,则order=1000,后面用于求x得最高位数字
		int copy = x;
		while(copy / 10 > 0){
			order = order * 10;
			copy = copy / 10;
		}
		int high = 0; //用于获取x的最高位
		int low = 0;//用于获取x的个位
		while(x != 0){
			high = x / order;
			low = x % 10;
			if(high != low){
				return false;
			}
			x = x % order / 10;//这一步很重要,用于获取掐头去尾后的x,例如1221-->22
			order = order / 100;//因为在上一步中x大小缩小了100倍,对应x的阶也应缩小100倍
		}
		return true;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: