This is a creation in Article, where the information may have evolved or changed.
Problem description
Reverse digits of an integer.
EXAMPLE1:X = 123, return 321
example2:x = -123, return-321
The test instructions is very clear and reverses an integer output.
Ideas
First of all, it is not an algorithm to consider the way that library functions first convert to string inversion.
The overall solution to the idea is to take out each number of integers in turn, then reverse, then assemble into integers. There are several points to consider:
- Take the lowest number.
num % 10
can be.
- Remove the bottom number.
num / 10
can be.
- Assemble integers. Define
sum := 0
, loop the number sequence, each time sum = sum * 10 + 数字
you can
- Overflow problem. The problem specifies that the integer is 32 bits, so the maximum value is
0x7FFFFFFF
, the minimum value is-0x80000000
Go implementation
Spents 6ms, beat 20% people with Golang.
var MINint=0x80000000var MAXint=0x7FFFFFFFFuncReverse(xint)int{sum:=0 for{leftdigits: = x/TenLastdigit: = x%Tenx = Leftdigitssum=sum*Ten+ Lastdigitif 0= = Leftdigits { Break} }if sum<-min | |sum> MAX {fmt. Println (sum)sum=0}return sum}