Leetcode 8 String to Integer (atoi) (C,c++,java,python)

Source: Internet
Author: User

Problem:

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please don't see below and ask yourself what is the possible input cases.

notes:  it is intended for the problem to be specified Vaguely (ie, no given input specs). You is responsible to gather all the input requirements up front.

update (2015-02-10):
the signature of The c++  function had been updated. If you still see your function signature accepts A const char *  argument, please click the reload Button   to Reset your code definition.

Spoilers alert ... click to show requirements for atoi.

Requirements for Atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, the starting from this character, takes a optional initial plus or minus sign followed by as many numerical digits as P Ossible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which is ignored and has no Effe CT on the behavior of this function.

If the first sequence of non-whitespace characters in STR isn't a valid integral number, or if no such sequence exists be Cause either str is empty or it contains only whitespace characters, no conversion is performed.

If No valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, Int_max (2147483647) or int_min ( -2147483648) is Returne D.


Solution:to deal with overflow, inspect the current number before multiplication. If the current number is greater than 214748364, we know it was going to overflow. On the other hand, if the current number was equal to 214748364, we know it would overflow only when the current digit is greater than or equal to 8.
Main topic:

Implementing the Atoi method in C language (string to Integer)

Problem-Solving ideas: The topic is simple, it is important to pay attention to some boundary conditions, such as determining the bounds, whether it contains illegal characters, the former space to remove
Java source code (spents 314ms):
public class Solution {private final static int int_max=2147483647;    Private final static int int_min=-2147483648;        public int myatoi (String str) {char[] chs = Str.tochararray ();        int index=0;        while (Index<str.length () && chs[index]== ") index++;        int flag=1;            if (Index<str.length () && chs[index]== '-') {flag=-1;        index++;        }else if (index<str.length () && chs[index]== ' + ') {index++;        } int res=0;            while (Index<str.length ()) {if (chs[index]< ' 0 ' | | chs[index]> ' 9 ') {return flag*res;            } int digit=chs[index]-' 0 ';            if (flag==1 && res*10.0+digit > Int_max) {return int_max;            }else if (flag==-1 &&-(res*10.0+digit) <int_min) {return int_min;            } res = Res*10+digit;        index++;    } return flag*res; }}


C Language Source code (spents 5ms):
int Myatoi (char* str) {    int flag=1,res=0,dig;    while (*str== ') str++;    if (*str== '-') {        flag=-1;        str++;    } else if (*str== ' + ') {        str++;    }    while (*STR) {        if (*str< ' 0 ' | | *str> ' 9 ') {            return flag*res;        }        dig=*str-' 0 ';        if (flag==1 && res*10.0+dig>int_max) {            return int_max;        } else if (flag==-1 &&-res*10.0-dig<int_min) {            return int_min;        }        res= Res*10+dig;        str++;    }    return flag*res;}


C + + source code (spents 17ms):
Class Solution {public:    int myatoi (string str) {        int index=0;        while (str[index]== ') index++;        int flag=1;        if (str[index]== '-') {            index++;            Flag=-1;        } else if (str[index]== ' + ') {            index++;        }        int res=0;        while (Index<str.size ()) {            if (str[index]< ' 0 ' | | str[index]> ' 9 ') {                return flag*res;            }            int digit=str[index]-' 0 ';            if (flag==1 && res*10.0+digit>int_max) {                return int_max;            } else if (flag==-1 &&-(res*10.0+digit) <int_min) {                return int_min;            }            res = res*10+digit;            index++;        }        return flag*res;}    ;


Python source code (spents 80ms):
Class solution:    # @param {string} str    # @return {integer}    def myatoi (self, str):        int_max=2147483647;i nt_min=-2147483648        index=0 while        Index<len (str) and str[index]== ": Index+=1        flag=1        if index< Len (str) and str[index]== '-':            index+=1            flag=-1        elif index<len (str) and str[index]== ' + ':            index+ =1        res=0 while        Index<len (str):            if str[index]< ' 0 ' or str[index]> ' 9 ': Return flag*res            Digit=ord (Str[index])-ord (' 0 ')            if Flag==1 and Res*10+digit>int_max:return Int_max            if Flag==-1 and res*10 +digit>-int_min:return int_min            res=res*10+digit            index+=1        return flag*res        


Leetcode 8 String to Integer (atoi) (C,c++,java,python)

Related Article

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.