String to Integer (atoi) -- LeetCode

Source: Internet
Author: User

 
This question is still about Integer processing. I mentioned in the Reverse Integer question that the focus of this question is not the problem itself, but the handling of the corner case. integers generally have two points, one is the problem of positive and negative symbols, and the other is the problem of integer out-of-bounds. The idea is simple: Remove unnecessary space characters and then read the symbols (note that both positive and negative numbers are possible, or there may be no symbols). Then, read the numbers in order, there are three conditions for the end condition: (1) The exception character appears (according to the C language standard, the exception character is truncated and the previous part is retained as the result); (2) number out of bounds (returns the nearest integer); (3) string ends. The Code is as follows:

public int atoi(String str) {    if(str==null)    {        return 0;    }    str = str.trim();    if(str.length()==0)        return 0;    boolean isNeg = false;    int i = 0;    if(str.charAt(0)=='-' || str.charAt(0)=='+')    {        i++;        if(str.charAt(0)=='-')            isNeg = true;    }    int res = 0;    while(i
 
  '9')            break;        int digit = (int)(str.charAt(i)-'0');        if(isNeg && res>-((Integer.MIN_VALUE+digit)/10))            return Integer.MIN_VALUE;        else if(!isNeg && res>(Integer.MAX_VALUE-digit)/10)            return Integer.MAX_VALUE;        res = res*10+digit;        i++;    }    return isNeg?-res:res;}
 
This question mainly deals with integer processing. Note that this question has been mentioned above, because it is a basic problem of C language and may still occur during the interview, which is relatively low-level, edge situations are critical, and tester interviews may be more common.

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.