Reverse Number
Given a signed 32-bit integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1]
, then return 0
.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Constraints:
-231 <= x <= 231 - 1
Solution
The time complexity of the algorithm is O(log(x)), where x is the input to the function. This is because in each iteration of the while loop, we’re dividing x
by 10
, effectively reducing the problem size by a factor of 10
. Hence, the number of iterations is proportional to the number of digits in x, which is log(x) in base 10.
The space complexity of the algorithm is O(1), which means it uses a constant amount of space. This is because we’re only using a fixed number of variables and not any data structures that grow with the size of the input. The integer result and the input x are the only variables being used, and their size does not change with different inputs.
Last updated