Reverse digits of an integer.
EXAMPLE1:X = 123, return 321
example2:x = -123, return-321
The general idea of the individual:
First determine whether it is an integer or a negative number, the flag record symbol (-1 or 1), take the absolute value and convert it to a string, reverse the string, convert the string to a number, and then multiply the flag to add the symbol. This solves the number at the end is 0, flipping over 0 for the beginning, and try to get rid of the first 0 questions. The code is as follows
1 intReverseintx) {2 Chars[ -],c[ -];3 intFlag =1;4 //Record Symbols5 if(X <0) {6Flag =-1;7 }8 //take absolute value9x =ABS (x);Ten //convert a number to a string Onesprintf (s),"%d", x); A - intLen =strlen (s); - intj =0; the for(intl=len-1; l>=0; l--) { - //C string + + traversal assignment, s string--traversal, the C string is the inverse of the s string -C[J] =S[l]; -J + +; + } - //Convert C string to digital +SSCANF (c,"%d",&x); A //add symbols to the resulting numbers atX *=Flag; - - returnx; -}
Results... Of course it is wrong Answer, fortunately there is error test data to you. (Details such as)
Looking at the test input and test output, you start to consider why you should output 0 after entering 1534236469. Check the data on the Internet, int max is 2147483647,and 1534236469 does not exceed int range, And also said to give an integer number, it is impossible to exceed the int range. That should be the result out of the int range. And after an int value is reversed, it is possible to exceed the int range. According to the test data, if the result of the conversion exceeds the int range, the output should be 0.
So since the result is likely to exceed the int range, then, when the string after the reverse order becomes a number, it cannot be received with the INT type variable, so I change the receive variable to a long type and judge that if the int range is exceeded, the result is assigned 0. The code is as follows:
1 intReverseintx) {2 Chars[ -],c[ -];3 intFlag =1;4 if(X <0) {5Flag =-1;6 }7x =ABS (x);8sprintf (s),"%d", x);9 Ten intLen =strlen (s); One intj =0; A for(intl=len-1; l>=0; l--) { -C[J] =S[l]; -J + +; the } - - LongRes; - +SSCANF (c,"%ld",&res); - + //determine if the int range is exceeded A if(Res > Int32_max | | Res <int32_min) { atres =0; - } - -Res *=Flag; - returnRes; -}
The result of the operation is correct.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode OJ] 7. Reverse Integer