Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Input: 121
Output: true
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
- mine
- Java
-
String
Runtime: 11 ms, faster than 23.00%, Memory Usage: 42.8 MB, less than 5.01% of Java online submissions
// O(N)time O(N)space // N is x's length public boolean isPalindrome(int x) { if(x < 0 || (x % 10 == 0 && x != 0)){ return false; } String s = String.valueOf(x); char[] array = s.toCharArray(); int i = 0; while(i <= array.length - 1 - i){ if(array[i] != array[array.length - 1 - i]){ return false; } i++; } return true; }
-
Math
Runtime: 6 ms, faster than 100.00%, Memory Usage: 38.8 MB, less than 64.50% of Java online submissions
// O(N)time O(1)space // N is x's length public boolean isPalindrome(int x) { if(x < 0 || (x != 0 && x % 10 == 0)){ return false; } int t = x; int res = 0; while(t > 0){ res = res * 10 + t % 10; t = t / 10; } return res == x; }
-
LinkedList
Runtime: 17 ms, faster than 9.62%, Memory Usage: 45 MB, less than 5.01% of Java online submissions
// O(N)time O(N)space // N is x's length public boolean isPalindrome(int x) { if (x < 0) { return false; } else if (x < 10) { return true; } else if (x % 10 == 0) { return false; } LinkedList<Integer> list = new LinkedList<>(); while (x > 0) { list.add(x % 10); x /= 10; } while (list.size() > 1) { if (!list.removeFirst().equals(list.removeLast())) { return false; } } return true; }
-
Math
Runtime: 9 ms, faster than 33.82%, Memory Usage: 41.9 MB, less than 6.33% of Java online submissions
// O(N)time O(1)space // N is x's length public boolean isPalindrome(int x) { if (x < 0) { return false; } else if (x < 10) { return true; } else if (x % 10 == 0) { return false; } int max = 1; while (x / max > 9) { max *= 10; } while (max >= 10 && x / max == x % 10) { x = x % max; x /= 10; max /= 100; } return max < 10; }
-
- Java
- the most votes
- Math
Runtime: 8 ms, faster than 41.65%, Memory Usage: 38.6 MB, less than 85.60% of Java online submissions
//O(N)time O(1)space // N is x's length public boolean isPalindrome(int x) { if (x < 0 || (x != 0 && x % 10 == 0)) return false; int rev = 0; while (x > rev) { rev = rev * 10 + x % 10; x = x / 10; } return (x == rev || x == rev / 10); }
- Math
- leetcode solution
-
Revert half of the number
Runtime: 6 ms, faster than 100.00%, Memory Usage: 38.8 MB, less than 64.50% of Java online submissions
//O(N)time O(1)space // N is x's length public boolean isPalindrome(int x) { if (x < 0 || (x % 10 == 0 && x != 0)) { return false; } int revertedNumber = 0; while (x > revertedNumber) { revertedNumber = revertedNumber * 10 + x % 10; x /= 10; } return x == revertedNumber || x == revertedNumber / 10; }
-