Idea: First keep a copy of the original value. Then reverse x by repeating dividing x by 10 and using a collector to keep adding the corresponding values. The compare the collector with the original value of x, if equals, return true, otherwise false.
Time: O(lgn) Space: O(1), where n is the value of x.
Code:
public class Solution {
public boolean isPalindrome(int x) {
if(x<0)
return false;
int ori=x;
int sum=0;
while(x>0)
{
sum=sum*10+x%10;
x=x/10;
}
return ori==sum;
}
}
No comments:
Post a Comment