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:
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 + pop
cause 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_VALUE
is represented as-2^31 = -2147483648
.
Palindrome Number
Link: https://leetcode.com/problems/palindrome-number/
Code:
Solution 1: stack and queue
Note that
Queue
is an abstract class in Java, so we need to useLinkedList
to implement it.Stack
methods:push
,pop
,peek
,isEmpty
. Refer to https://www.geeksforgeeks.org/stack-class-in-java/ for more details.Queue
methods: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
int
number;when the original number is less than the reversed number, it means we've processed half of the number digits.
Last updated