Skip to content

Instantly share code, notes, and snippets.

@amilcar-andrade
Created May 25, 2017 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amilcar-andrade/de4ef121baef87da17b2fb2bfde0adc6 to your computer and use it in GitHub Desktop.
Save amilcar-andrade/de4ef121baef87da17b2fb2bfde0adc6 to your computer and use it in GitHub Desktop.
isPalindrome implementation
import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
456654 => true
3769 => false
0-9 => true
numbers < 0 => false
*/
class Solution {
public static void main(String[] args) {
System.out.println(isPalindrome(456654));
System.out.println(isPalindrome(3769));
System.out.println(isPalindrome(0));
System.out.println(isPalindrome(-1));
}
public static boolean isPalindrome(int n) {
if (n < 0) {
return false;
}
if (n < 10) {
return true;
}
// 456654 % 10 --> 4
// time : O(n) where n is number of digits
while (n > 10) {
int lsd = n%10;
int base = (int)Math.pow(10,(int)Math.log10(n));
int msd = (int)(n/base);
if (lsd != msd) {
return false;
}
n -= msd*base; // chops off left (msd)
n = n / 10; // chops off right (lsd)
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment