Test instructions
Reverse digits of an integer.
EXAMPLE1:X = 123, return 321
example2:x = -123, return-321
Analysis:
The idea is very simple, pay attention to special cases such as 10,100 and int overflow situation can be;
Start with an array to save you first, and then multiply the corresponding coefficients to make the result, but the code is lengthy and cost space;
A while loop can be used directly;
Code Listing 1:
1 classSolution {2 Public:3 intReverseintx) {4 Long Longresult =0;5 while(X! =0) {6 inttemp = x%Ten;7X/=Ten;8result = result *Ten+temp;9 if(Result >0x7FFFFFFF|| Result <-0x7FFFFFFF) {Ten return 0; One } A } - returnresult; - } the};
Viewing the discussion area, it is found that there is a kind of realization method without 0x7fffffff judgment, as reference;
Code Listing 2:
1 classSolution {2 Public:3 intReverseintx) {4 intresult =0;5 while(X! =0) {6 inttemp = x%Ten;7X/=Ten;8 intNewresult = result *Ten+temp;9 if((newresult-temp)/Ten!=result) {Ten return 0; One } Aresult =Newresult; - } - returnresult; the } -};
LeetCode7 Reverse Integer