Question (in Chinese): http://ac.jobdu.com/problem.php?pid=1508
Question Name: String To Int
Question Description: Convert the input string into an integer. The input string may or may not represent a valid and non-overflow integer.
Input: the input might contain multiple test cases. Each line is a test case (-10000000 <= integer <= 10000000).
Output: print the integer if the input string is a valid and non-overflow integer. Otherwise, print “My God”.
1 2 3 4 5 6 7 8 | Input: 5 -5 +8 Output: 5 -5 8 |
The solution is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | /*---------------------------------------------------------------- * Author: Sheng Yu - codesays.com * Written: 09/13/2014 * Last updated: 09/13/2014 * * Filename: StringToInt.java * Compilation: javac StringToInt.java * Execution: java StringToInt * JDK Used: 1.7 *----------------------------------------------------------------*/ import java.util.Scanner; /** * Convert a string into an integer. * @author Sheng Yu codesays.com */ public class StringToInt { /** * Convert the input string into an integer. * @param str the string to parse as integer. * @exception IllegalArgumentException when the input string is not a legal * integer. * @return the integer, whose string representation is the input str. */ public static int str2int(String str) { if (str == null) throw new IllegalArgumentException(); int sign = 1; int result = 0; int MAX = 10000000; char[] st = str.toCharArray(); int index = 0; int nextDigit = 0; // Get the sign. if (st[0] == '+') { sign = 1; ++index; } else if (st[0] == '-') { sign = -1; ++index; } // Get the value while (index < st.length) { // Check whether the next char is number. if (!Character.isDigit(st[index])) throw new IllegalArgumentException(); // Check whether there is an overflow. nextDigit = (int) st[index] - 48; if (MAX / 10 >= result && MAX - result * 10 >= nextDigit) { result = result * 10 + nextDigit; } else { throw new IllegalArgumentException(); } ++index; } return result * sign; } /** * Stub for test. * @param args the command line arguments. */ public static void main(String[] args) { Scanner sin = new Scanner(System.in); String str = null; int value = 0; while (sin.hasNextLine()) { str = sin.nextLine(); try { value = str2int(str); System.out.println(value); } catch (IllegalArgumentException e) { System.out.println("My God"); } } } } |