Math
Add Two Numbers
See https://notes.jinjunliu.com/8_leetcode/8.4_linked_list/#add-two-numbers
Reverse Integer
Link: https://leetcode.com/problems/reverse-integer/
Code:
class Solution {
public int reverse(int x) {
int rev = 0, pop;
while (x != 0) {
pop = x % 10;
x = x / 10;
if (rev > Integer.MAX_VALUE / 10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE / 10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}Time Complexity: {{< katex >}}O(\log(x)){{< /katex >}}. There are roughly {{< katex >}}\log_{10}(x){{< /katex >}} digits in x.
Space Complexity: O(1).
If
rev * 10 + popcause overflow, then it must be thatrev >= Integer.MAX_VALUE / 10;If
rev > Integer.MAX_VALUE / 10, then it is guaranteed to overflow.If
rev = Integer.MAX_VALUE, then it will overflow if and only ifpop > 7, because2^31 - 1 = 2147483647 = Integer.MAX_VALUE.Similar logic applies to
Integer.MIN_VALUE.Integer.MIN_VALUEis represented as-2^31 = -2147483648.
Palindrome Number
Link: https://leetcode.com/problems/palindrome-number/
Code:
Solution 1: stack and queue
Note that
Queueis an abstract class in Java, so we need to useLinkedListto implement it.Stackmethods:push,pop,peek,isEmpty. Refer to https://www.geeksforgeeks.org/stack-class-in-java/ for more details.Queuemethods:add,poll,peek,isEmpty. Refer to https://www.geeksforgeeks.org/queue-interface-java/ for more details.
Solution 2: reverse half of the integer and compare
we only revert half of the
intnumber;when the original number is less than the reversed number, it means we've processed half of the number digits.
Last updated