24.07.2021
小白一枚,文章仅当日记本记录学习进度 ;)
如被浏览,请多多指教,非常感谢大家纠错与建议!
(因留学顺便练习英语,所以用英文笔记,并无他意)
- Could you solve it without converting the integer to a string?
Solution 1 - reverse the number (Java)
Runtime: 7 ms, faster than 69.75% of Java online submissions for Palindrome Number.
Memory Usage: 38.7 MB, less than 31.51% of Java online submissions for Palindrome Number.
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) return false;
int rev = 0, source = x;
while (x != 0) {
int pop = x % 10;
rev = rev * 10 + pop;
x /= 10;
}
return rev == source;
}
}
- use two pointers (Java)
Runtime: 8 ms, faster than 45.06% of Java online submissions for Palindrome Number.
Memory Usage: 38.1 MB, less than 93.16% of Java online submissions for Palindrome Number.
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) return false;
List<Integer> container = new ArrayList<>();
while (x != 0) {
container.add(x % 10);
x /= 10;
}
// create two pointers
int left = 0, right = container.size() - 1;
while (left < right) {
if (container.get(left) != container.get(right)) return false;
left ++;
right --;
}
return true;
}
}