Created
May 4, 2016 20:57
-
-
Save edalorzo/f23aa9b6a1d4a8aac17777bb6eecb7f8 to your computer and use it in GitHub Desktop.
Largest Palindrome Number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Palindrome { | |
private static boolean isPalindrome(long n) { | |
return reverse(n) == n; | |
} | |
private static long reverse(long n) { | |
long rev = 0L; | |
while (n > 0) { | |
long d = n % 10; | |
n = n / 10; | |
rev = rev * 10 + d; | |
} | |
return rev; | |
} | |
/** | |
* Finds the largest palindrome number not greater than n. | |
*/ | |
public long largest(long n) { | |
long max = 0; | |
for (int j = 100; j < 1000; j++) { | |
for (int k = 100; k < 1000; k++) { | |
long p = j * k; | |
if (p >= n) { | |
break; | |
} | |
if (isPalindrome(p)) { | |
max = Math.max(max, p); | |
} | |
} | |
} | |
return max; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment