首页 > 其他 > 详细

leetcode-9 Palindrome Number

时间:2015-04-04 09:15:39      阅读:122      评论:0      收藏:0      [点我收藏+]


问题描述:

Determine whether an integer is a palindrome. Do thiswithout extra space.

click to showspoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string,note the restriction of using extra space.

You could also try reversing an integer. However, if youhave solved the problem "Reverse Integer", you know that the reversedinteger might overflow. How would you handle such case?

There is a more generic way of solving this problem.

 

问题分析:简单问题,取相应位数字进行比较就行了

代码:

public class Solution {
    public boolean isPalindrome(int x) {
		//特殊值判断
		if(x < 0)
			return false;
		if(x < 10)//只有一位
			return true;
			
		//计算x的10进制长度
		int temp = x;
		int left_base = 1;
		int right_base = 1;
		while((temp /= 10) != 0)
		{
			left_base *= 10;
		}
		
		while(left_base > right_base)
		{
			//相应位进行比较即可
			if((x / left_base % 10) != (x / right_base % 10))
			{
				return false;
			}
			
			left_base /= 10;
			right_base *= 10;
		}
		return true;   
    }
    
    public static void main(String[] args)
    {
    	int x = 12;
    	System.out.println(new Solution().isPalindrome(x));
    }
}

leetcode-9 Palindrome Number

原文:http://blog.csdn.net/woliuyunyicai/article/details/44859843

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!