Determine whether an integer is a palindrome. Do this without extra space.
Thoughts
Problems related with numbers are frequently solved by / and %. No need of extra space is required. This problem is similar with the Reverse Integer problem.
public boolean isPalindrome(int x) { //negative numbers are not palindrome if (x < 0) return false; // initialize how many zeros int div = 1; while (x / div >= 10) { div *= 10; } while (x != 0) { int left = x / div; int right = x % 10; if (left != right) return false; x = (x % div) / 10; div /= 100; } return true;
}
Alternative Solution:
Credits go to Dev who suggested a recursive solution (if extra stack space does not count as extra space), which is pretty neat too.
Credits go to Dev who suggested a recursive solution (if extra stack space does not count as extra space), which is pretty neat too.
Read full article from LeetCode – Palindrome Number (Java)
No comments:
Post a Comment