BruteForce
1 | class Solution { |
Remarks:
- TC: $O(|n|)$, SC: $O(1)$.
- Takes too long time. Time Limit Exceeded.
Divide and Conquer
1 | class Solution { |
Remarks:
TC: $O(\log N)$, SC: $O(\log N)$
How it works? Consider how we find the binary of a decimal number, by divisions.
Takepow(2,10)as an example:1
2
3
4
5
6
72 | 10 ...0
-----
2 | 5 ...1
----
2 | 2 ...0
---
1So (10)dec = (1010)bin, which means $10 = 8 + 2 = 2^3 + 2 ^ 1$.
$2^{10}=2^{2^3}\cdot 2^{2^1}$
That’s why we only
result *= xwhenN % 2 == 1, as there’s bit1in the binary number.