1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import static junit.framework.TestCase.assertTrue;
public class PalindromeNumber { public boolean isPalindrome(int x) { if (x == Integer.MIN_VALUE || x < 0) { return false; } if (x < 10) { return true; } int length = 0; int tmp = x; while (tmp >= 10) { length++; tmp /= 10; } for (int i = 0; i <= length / 2; i++) { int mod = (x / (int) (StrictMath.pow(10, i))) % 10; int t = (x / (int) (StrictMath.pow(10, length - i))) % 10; if (mod != t) { return false; } } return true; } @Test public void test() { assertTrue(!isPalindrome(10)); assertTrue(isPalindrome(11)); assertTrue(isPalindrome(101)); assertTrue(isPalindrome(313)); assertTrue(!isPalindrome(1000021)); assertTrue(isPalindrome(1001)); } }
|