ITeye博客

判断一个数字是否是回文

andyjojo · 2011-06-09 12:00 · Java · 编程语言 · Markdown

最近碰到一个题目,其中一步判断数字是否为回文 由于题目要求是最短时间实现,不要考虑实现本身的效率

1 如果直接去实现,就是比较数字的最高位值和最低位,然后再。。


public boolean isP(int x){
	int bit = 1;
	int temp = 10;
	while(x>temp){bit++;temp*=10;}
	if(x==temp)bit++;
        // bit为数值位数
	int temp1, temp2;
	for(int i=0;i<bit/2;i++){
		temp = (int)Math.pow(10,i);
		temp1 = x%(temp*10)/temp;
		temp = (int)Math.pow(10,bit-i-1);
		temp2 = x%(temp*10)/temp;
		if(temp1==temp2)continue;
		else return false;
	}
	return true;
}

这个方法是数值比较,实现时很容易出错,实现时间比较长,其实效率也不高

2 换一种思路,把数值转为char,再比较,


public boolean isP(int x){
	char[] temp = (""+x).toCharArray();
	for(int i=0; i<temp.length/2; i++){
		if(temp[i]!=temp[temp.length-i-1])
			return false;
	}
	return true;
}

虽然都很简单,但是仅以此文告诫自己动手写代码之前要三思

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。