1+ package com .rampatra .strings ;
2+
3+ /**
4+ * @author rampatra
5+ * @since 2019-04-01
6+ */
7+ public class StringToInteger {
8+
9+ /**
10+ * This method converts a {@code String} to an {@code int}. It assumes the {@code string} contains ASCII
11+ * characters only.
12+ *
13+ * @param str the input string, for example, 0, 123, +123, -123, etc.
14+ * @return the equivalent integer.
15+ */
16+ private static int getIntegerFromString (String str ) {
17+ int number = 0 ;
18+ int digit ;
19+ char ch ;
20+ int weight = 0 ;
21+ boolean isNegative = false ;
22+
23+ // remove all leading and trailing whitespaces
24+ str = str .trim ();
25+ if (str .length () == 0 ) {
26+ throw new NumberFormatException ("Empty string" );
27+ }
28+
29+ for (int i = str .length () - 1 ; i >= 0 ; i --) {
30+ ch = str .charAt (i );
31+ if (ch == '-' && i == 0 ) {
32+ isNegative = true ;
33+ continue ;
34+ } else if (ch == '+' && i == 0 ) {
35+ continue ;
36+ }
37+
38+ digit = ch - '0' ;
39+
40+ if (digit < 0 || digit > 9 ) {
41+ throw new NumberFormatException ("Invalid characters" );
42+ }
43+
44+ number += digit * (Math .pow (10 , weight ++));
45+ }
46+ return isNegative ? -number : number ;
47+ }
48+
49+ public static void main (String [] args ) {
50+ // normal cases
51+ System .out .println (getIntegerFromString ("0" ));
52+ System .out .println (getIntegerFromString ("123" ));
53+ System .out .println (getIntegerFromString ("0123" ));
54+ System .out .println (getIntegerFromString ("+123" ));
55+ System .out .println (getIntegerFromString ("-123" ));
56+
57+ // error cases
58+ System .out .println (getIntegerFromString ("1-23" ));
59+ System .out .println (getIntegerFromString ("" ));
60+ System .out .println (getIntegerFromString (" " ));
61+ System .out .println (getIntegerFromString (" " ));
62+ System .out .println (getIntegerFromString ("123L" ));
63+ }
64+ }
0 commit comments