In order to improve the efficiency of the interview process, it is convenient to write a function in Java to convert the string into an integer. Give me a quick look at the code basics.
Requirement: Do not call conversion functions such as parseint. A bitwise reading of the characters in a string converts the string to an integer,
Regardless of the integer overflow problem, the given input must be legal input does not contain illegal characters, the string ends without spaces,
Consider that the beginning of a string may have a sign. public int stringtoint (String str)
Import javax.net.ssl.sslcontext;/** * string to int * @author IT * @Date October 16, 2018 */public class S tringtoint {public static void main (string[] args) {String s = "2018"; try {System.out.println ("Convert result" +parse (s));} catch (Ex Ception e) {e.printstacktrace ();}} public static int Parse (String s) throws exception{int result = 0; if (s = = NULL | | s.length () = = 0) {throw new Exception ("string is empty"); } String S1 = s;//if (S.startswith ("-")) {//s1 = s.substring (1, s.length ());/} for (int i = 0; i < s1.length (); i++) {if (i==0) {if (S1.charat (i) = = '-') {continue; }}else{if (S1.charat (i) > ' 9 ' | | S1.charat (i) < ' 0 ') {throw new Exception ("Malformed string"); }} result = result * 10; result = (Result + S1.charat (i))-' 0 '; SYSTEM.OUT.PRINTLN ("Every digit:" +s1.charat (i)); SYSTEM.OUT.PRINTLN ("Cumulative result per Time:" +result); } return result;}}
The function of turning a string into an integer give me a look, simply look at the code basics. Requirements: Do not call conversion functions such as parseint