1. Title
Reverse Integer (Flip number)
2. Address of the topic
https://leetcode.com/problems/reverse-integer/
3. Topic content
English: Reverse digits of an integer.
English: Flip a positive integer to create a new number
For example: x = 123, return 321;x = -123, return-321
4, a defective method (not AC)
A good idea is to first convert the input number to a string, then flip the string back into a number. This method is feasible for the general number, and its disadvantage is that when faced with some very large integers, the rollover can cause overflow and cannot be judged. The Java code is as follows:
/** * function Description:leetcode 7 - reverse integer * developer:tsybius * Development Date: September 20, 2015 */public class solution { / ** * Invert numbers * @param x reversed numbers * @return Reversed numbers */ Public int reverse (int x) { if (x == 0) { return 0; } string str = string.valueof (x >= 0 ? x : -x); str = (new StringBuilder (str)). Reverse (). toString ();nbsp; if ( x > 0) { return Integer.parseint (str); } else { return integer.parseint ("-" + str); } }}
5. Methods of Solving problems
A more insurance method, that is, when the calculation of a long type, after the completion of the calculation to see whether the upper bound or the lower bound of the integer, more than the return of the integer type of the maximum or minimum value, or cast directly to the integer type after the return. The Java code is as follows:
/** * function Description:leetcode 7 - reverse integer * developer:tsybius * Development Date: September 20, 2015 */public class solution { / ** * Invert numbers * @param x reversed numbers * @return Reversed numbers */ Public int reverse (int x) { if (x == 0) { return 0; } //is first converted to a positive integer calculation boolean sign = x > 0 ? true : false; x = sign ? x : x * ( -1); //calculates results using long integer types, preventing overflow errors long result = 0L; while (True) { Result += x % 10; x /= 10; if (x != 0) { result *= 10; } else { break; } } //The result, compare whether the integer maximum/minimum value is exceeded result = sign ? result : result * ( -1); if (result > integer.max_value | | result < integer.min_value) { return 0; } else { return (int) result; } }}
The code for this method can also be further streamlined, and the following code reduces the number of lines of code:
/** * function Description:leetcode 7 - reverse integer * developer:tsybius * Development Date: September 20, 2015 */public class solution { / ** * Invert numbers * @param x reversed numbers * @return Reversed numbers */ Public int reverse (int x) { long result = 0; while (x!=0) { result = result * 10 + x % 10; x /= 10; } return (Result > integer.max_value | | result < integer.min_value) ? 0 : (int) result; } }
END
Leetcode:reverse Integer-Flips the number