[Leetcode] 008. String to Integer (easy) (C++/java/python)

Source: Internet
Author: User

Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode

008.string_to_integer (Easy) links

Title: https://oj.leetcode.com/problems/string-to-integer-atoi/
Code (GitHub): Https://github.com/illuz/leetcode

Test Instructions

Converts a string to type int.

Analysis

Note If you go out of range, the nearest int is returned.
If: 2147483648 is greater than Int_max (2147483647), return 2147483647.

Before can use sscanf lazy, recently updated case is stuck.
Some points to note:

    1. Skip the preceding spaces, \t,\n
    2. Scope definition

Regular expressions using Python can be easily handled.

Code

C++:

Class Solution {public:    int atoi (string str) {int ret = 0;bool overflow = False;int sign = 1;//default is ' + ' int i = 0;int len = Str.length (), while (I < Len && (str[i] = = ' | | str[i] = = ' \ n ' | | str[i] = = ' \ t ')) ++i;if (i = = Len return 0;//get signif (str[i] = = '-') {++i;sign =-1;} else if (str[i] = = ' + ') ++i;while (i < len) {if (!isdigit (str[i ]) break;if (sign = = 1 && ret > (Int_max-(str[i]-' 0 '))/10) | | (sign = =-1 &&-ret < (int_min + (str[i]-' 0 '))/10)) {overflow = True;break;} RET = RET * + (Str[i]-' 0 '); ++i;} if (overflow) ret = (sign = = 1)?  Int_max:int_min;elseret *= sign;return ret;    };


Java:

public class Solution {public int atoi (String str) {int ret = 0;        Boolean overflow = false;        int sign = 1;//The default is ' + ' int i = 0;        int len = Str.length ();        while (I < Len && (Str.charat (i) = = ' | | Str.charat (i) = = ' \ n ' | | str.charat (i) = = ' \ t ')) ++i;        if (i = = len) return 0;            Get sign if (Str.charat (i) = = '-') {++i;        sign =-1;        } else if (Str.charat (i) = = ' + ') ++i;            while (I < len) {if (Str.charat (i) < ' 0 ' | | str.charat (i) > ' 9 ') break;                    if (sign = = 1 && ret > (Integer.max_value-(Str.charat (i)-' 0 ')/10) | | (sign = =-1 &&-ret < (Integer.min_value + (Str.charat (i)-' 0 '))/10))                {overflow = true;            Break            } RET = ret * + (Str.charat (i)-' 0 ');        ++i;         } if (overflow)   RET = (sign = = 1)?        Integer.MAX_VALUE:Integer.MIN_VALUE;        else ret *= sign;    return ret; }}


Python:

Class solution:    # @return An integer    def atoi (self, str):        str = Str.strip ()        if not str:            return 0        Max_int = 2147483647        min_int = -2147483648        ret = 0        overflow = False        pos = 0 Sign        = 1        if Str[pos]  = = '-':            pos + = 1 Sign            = 1        elif Str[pos] = = ' + ':            pos + = 1 for        i in range (POS, len (str)):            If Not Str[i].isdigit ():                break            ret = ret * + int (str[i])            If isn't min_int <= sign * ret <= MAX_INT:
   overflow = True                break        if overflow:            return max_int if sign = = 1 Else min_int        else:            return sign * RET


Use Python's regular expression:

Class solution:    # @return An integer    def atoi (self, str):        str = str.strip ()        str = re.match (R ' ^[+-]?\d+ ', STR). Group ()        max_int = 2147483647        min_int = -2147483648        try:            ret = INT (str)            if ret > max_int:                return max_int            elif ret < min_int:                return min_int            else:                return ret        except:            return 0


[Leetcode] 008. String to Integer (easy) (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.