四刷 07/2022
Version #1 Reverse the whole number - slower
Time O(logX)
Space O(1)
Runtime: 18 ms, faster than 28.91% of Java online submissions for Palindrome Number.
Memory Usage: 44.6 MB, less than 53.23% of Java online submissions for Palindrome Number.
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int original = x;
long reversed = 0l;
while (x > 0) {
reversed = reversed * 10 + x % 10;
x /= 10;
}
return reversed == original;
}
}
Version #2 Reverse half of the number
写了bug就是当数是10的倍数的时候也是一定是false的
Time O(logX)
Space O(1)
Runtime: 19 ms, faster than 24.56% of Java online submissions for Palindrome Number.
Memory Usage: 44.6 MB, less than 57.89% of Java online submissions for Palindrome Number.
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || x % 10 == 0 && x != 0) {
return false;
}
int reversed = 0;
while (x > reversed) {
reversed = reversed * 10 + x % 10;
x /= 10;
}
return reversed == x || reversed / 10 == x;
}
}
70.40 %
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0)) {
return false;
}
int reversed = 0;
while (reversed < x) {
reversed = reversed * 10 + x % 10;
x = x / 10;
}
return reversed == x || reversed / 10 == x;
}
}
一刷 //Compare half of the digits in x, so don't need to deal with overflow.
There are 2 cases, number of digits is an odd number or even number
The number can't be a multiple of ten.
43.90%
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || x != 0 && x % 10 == 0) return false;
int reverse = 0;
while (x > reverse) {
reverse = reverse * 10 + x % 10;
x = x / 10;
}
return reverse == x || x == reverse / 10;
}
}
二刷 6/3/2018
beats 34.61 %
class Solution {
public boolean isPalindrome(int x) {
if (x == 0) return true;
if (x < 0 || x % 10 == 0) return false;
int reverse = 0;
// 121 split from n / 2 + 1, reverse the left half of the number
// 1, 21
// origin = 312, reverse = 31
// if reverse == origin || reverse == origin / 10 -> true
while (reverse < x) {
reverse = reverse * 10 + x % 10; // 1
x = x / 10; // 12
}
return reverse == x || x == reverse / 10;
}
}
No comments:
Post a Comment