卖萌的弱渣

I am stupid, I am hungry.

String to Integer

Implement atoi to convert a string to an integer.

Hint

Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes

It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Requirements for atoi

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

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because 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 returned.

Solution

  • Java: 不用考虑小数
(atoi.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Solution {
    public int myAtoi(String str) {
        // empty
        if (str.length()==0)
            return 0;
        // space
        str = str.trim();

        // sign
        int sign = 1;
        int index = 0;
        // case: "+1"
        if (str.charAt(index)=='-' || str.charAt(index)=='+'){
            sign = str.charAt(index)=='+'?1:-1;
            index++;
        }

        // convert str to int
        int num = 0;
        while(index<str.length()){
            int digit = str.charAt(index)-'0';
            if (digit < 0 || digit > 9)
                break;
            // 判断越界问题
            if (Integer.MAX_VALUE/10 < num || (Integer.MAX_VALUE/10==num && Integer.MAX_VALUE%10<digit))
                return sign==1?Integer.MAX_VALUE:Integer.MIN_VALUE;

            num = num*10 +digit;
            index++;
        }
        return sign*num;

    }
}
  • Python
(String-to-Integer.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        nums = ['0','1','2','3','4','5','6','7','8','9']
        index = 0
        l = len(str)
        neg = 1

        # find the first non-space char
        while index < l and str[index] == ' ':
            index += 1
        if index == l:
            return 0

        # "+" or "-"
        if str[index] == '-':
            neg = -1
            index += 1

        if str[index] == '+':
            index += 1

        # get integer part
        integer = 0
        decimal = 1
        while index < l and str[index] in nums:
            integer = 10*integer + int(str[index])
            index += 1
        # maybe the decimal part
        if str[index] == '.':
            while index<l and str[index] in nums:
                integer = integer + int(str[index])/(10**decimal)
                index += 1
                decimal += 1

        integer = neg * integer
        if integer > sys.maxint:
            return sys.maxint
        elif integer < -sys.maxint:
            return -sys.maxint
        else:
            return integer