Skip to content

Instantly share code, notes, and snippets.

@luoxiaoxun
Created July 9, 2013 06:54
Show Gist options
  • Save luoxiaoxun/5955219 to your computer and use it in GitHub Desktop.
Save luoxiaoxun/5955219 to your computer and use it in GitHub Desktop.
Determine whether an integer is a palindrome. Do this without extra space. 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 th…
C++:
class Solution {
public:
bool isPalindrome(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(x<0) return false;
int base=1;
while(x/base>=10) base *=10;
while(x){
int left=x/base;
int right=x%10;
if(left!=right) return false;
x=(x%base)/10;
base=base/100;
}
return true;
}
};
Java:
public class Solution {
public boolean isPalindrome(int x) {
// Start typing your Java solution below
// DO NOT write main() function
if(x<0) return false;
int base=1;
while(x/base>=10) base *=10;
while(x>9){
int left=x/base;
int right=x%10;
if(left!=right) return false;
x=(x%base)/10;
base=base/100;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment