A function that turns a string into an integer show me a simple look at the code basics. Requirements: Do not call conversion functions such as parseint

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.