func reverse(x int) int {
var neg bool
if x < 0 {
neg = true
x = x * -1
}
revX := getReversed(x)
if neg == true {
return revX * -1
}
return revX
}
func getReversed(x int) int {
var rev, lastDigit int
for x > 0 {
lastDigit = x % 10
x = x / 10
rev = rev*10 + lastDigit
}
if rev > (math.MaxInt32) {
return 0
}
return rev
}-
reverse(x int) intFunction:- This function takes an integer
xas input and returns the reversed integer. - It first checks if
xis negative. If it is, it sets a boolean variablenegtotrueand convertsxto its absolute value. - It then calls the
getReversed(x)function to reverse the digits of the (now positive)x. - Finally, it checks the
negflag. If the original number was negative, it negates the reversed integerrevXbefore returning it. Otherwise, it returnsrevXdirectly.
- This function takes an integer
-
getReversed(x int) intFunction:- This function takes a positive integer
xas input and returns its reversed value. - It initializes two integer variables:
rev(to store the reversed integer) andlastDigit. - It uses a
forloop to iterate through the digits ofx. - Inside the loop:
lastDigitis extracted using the modulo operator (% 10).xis divided by 10 (integer division) to remove the last digit.revis updated by multiplying it by 10 and addinglastDigit. This effectively shifts the existing digits ofrevto the left and adds the new digit to the right.
- It checks for integer overflow by comparing
revtomath.MaxInt32. Ifrevexceeds this maximum value, it returns 0. - It returns the reversed integer
rev.
- This function takes a positive integer
Time and Space Complexity
Time Complexity:
getReversed(x int): Theforloop iterates once for each digit in the input integerx. The number of digits inxis proportional to log10(n), where n is the absolute value ofx. Therefore, the time complexity ofgetReversedis O(log10(n)).reverse(x int): This function callsgetReversedand performs constant-time operations. Thus, the time complexity ofreverseis also O(log10(n)).
Space Complexity:
-
getReversed(x int): The function uses a constant amount of extra space for the variablesrevandlastDigit. Therefore, the space complexity is O(1). -
reverse(x int): This function uses a constant amount of extra space for the variablenegand the return value. Therefore, the space complexity is O(1). -
Overall, the space complexity of the code is O(1).
Time Complexity:
- O(log10(n)), where n is the absolute value of the input integer.
Space Complexity:
- O(1) (constant space).