Skip to content

Instantly share code, notes, and snippets.

@3014zhangshuo
Created August 14, 2020 03:51
Show Gist options
  • Save 3014zhangshuo/fcd293f9980494d3feefc41ce35d9dff to your computer and use it in GitHub Desktop.
Save 3014zhangshuo/fcd293f9980494d3feefc41ce35d9dff to your computer and use it in GitHub Desktop.
class Solution
def reverse_integer(x)
# for the last result
sign = x < 0 ? -1 : 1
x_clone = x.abs.dup
x_result = 0
while x_clone > 0
x_result = (x_result * 10) + x_clone % 10
x_clone /= 10
end
# such as 123
# 0 3 12
# 30 2 1
# 32 1 0
x_result = x_result * sign
two_pow_31 = 2**31
x_result < two_pow_31 - 1 && x_result > two_pow_31*-1 ? x_result : 0
end
def reverse(x)
copy = x.dup
result = copy.to_s.reverse.to_i
result = -result if x < 0
return 0 if result < -2**31 || result > 2**31 - 1
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment