# [9 ms JAVA] Beats 99.5 java solutions, easy to understand

• ``````public class Solution {
static int v;
public static boolean isPalindrome(int x) {
//optimizations
if(x<0) return false;
if(x<10) return true;
if(x%10==0) return false;
if(x<100&&x%11==0) return true;
if(x<1000&&((x/100)*10+x%10)%11==0) return true;

//actual logic
v=x%10;
x=x/10;
while(x-v>0)
{
v=v*10+x%10;
x/=10;
}
if(v>x){v/=10;}
return v==x?true:false;
}
}``````

• 来个中文解释。

楼主的大概逻辑是，比如 1234321；
每次通过除以10和对10取余来保存下前半部分x和后半部分v，比如 x = 123432, v=1;
直到x=123，v=1234的时候，循环结束，再通过 v/10 == x，来判断数是不是回环的。

• Thanks @wmlhust for the explanation in Chinese :)

• Is v using extra space?

• @Rhodey As long as its a constant space i think it should be fine.

• Really nice solution :)

• When I use your code to test, but I got 246ms. Why why why? Anyone can tell me？Is LeetCode become slower?

• @yuwang3 It would be caused by the updates of test cases?... I had one solution for another problem which was [3 ms] 6 months ago but [35 ms] for now, even though I just copy and paste my previous code.

• @wmlhust 厉害了我的哥

• just copied the code and got a runtime of 320ms, someone tell me why :/

• @JunchenSu You can submit the code more than once. Sometimes the performance of server is very slow and then you can get different result.

• Is this variable v, not belongs to "extra space"?

• @zhugejunwei And as Leetcode officially pronounced, we cannot use static for Leetcode questions.

• @zhugejunwei

"Extra Space": To understand this you need to understand what constant space means in terms of an algorithm.

Constant space means that the amount of space that your algorithm uses is independent of the input parameters. Say you are given an array of size n. If the amount of space your algorithm uses scales with n, then it's not constant. If your algorithm always uses a fixed amount of space (5 variables, an array of fixed size: 100, 300, 5000, etc..), you are golden. [ ref: https://discuss.leetcode.com/topic/429/meaning-of-constant-space-complexity/2 ]

In this algorithm, the complexity is `O(d)` where `d` is the number of digits in integer `x`. Integer `v` is not related to `d` in any way, thus this is a constant space solution.

Static functions/variable:

https://leetcode.com/faq/ warns against using them and they should be avoided in any production ready(real life) code, but there is no guideline for not using them. As long as the code passes the tests it's okay. It's the algorithm that matters.

• @everlasting.puneet Got it. Thank you for the detailed and patient explanation.

• Thanks,Really nice solution :)

• You are so genius of this idea!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.