LeetCode 8 String to Integer (atoi) (C,C++,Java,Python)

Problem:

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.

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, 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:

To deal with overflow, inspect the current number before multiplication. If the current number is greater than 214748364, we know it is going to overflow. On the other hand, if the current number is equal to 214748364, we know that it will overflow only when the current digit is greater than or equal to 8.
题目大意:

实现C语言中的atoi方法(字符串转为整数)

解题思路:

题目简单,重要的是注意一些边界条件,如判定越界,是否含有非法字符,前空格去掉等
Java源代码(用时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语言源代码(用时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++源代码(用时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源代码(用时80ms):

class Solution:
    # @param {string} str
    # @return {integer}
    def myAtoi(self, str):
        INT_MAX=2147483647;INT_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
        


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值