LeetCode【9】. Palindrome Number

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 you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

判断一个int是否为回文。

一、思路1:

首先获取int长度,再从两头往中间扫描,,将对称的元素成对进行比较。代码如下,但是Time Limit Exceeded超时了。

public class Solution {public boolean isPalindrome(int x) {int xl;if(x<0)//1.小于0return false;for(xl = 1;x/(xl*10)>0;xl++) //2. 得到x的长度;if(xl==1)//3.x为个位数时直接返回(因为后续处理个位数时会使分母为0,故单独处理)return true;for(int i=2;(xl/2)>=i;i++){if(x%(i*10)/((i-1)*10) == x%((xl-i+1)*10)/((xl-i)*10)) //4.分别取对称的两个数进行比较{}elsereturn false;}return true;}} 二、思路2 复制将给定int从低位往高位开始,复制为另外一个高位至低位,得到一个给定值的反序。再比较两者是否相等。意思就是拿个镜子,然后照出镜子里跟自己左右相反的自己。如果是自己是完全对称的(这里是回文),那例外两个看一起一定一模一样的。

会得到最大的满足,因为它填补了你的空虚。

LeetCode【9】. Palindrome Number

相关文章:

你感兴趣的文章:

标签云: