LeetCode---(8)String to Integer (atoi)

转载 2015年07月10日 22:11:45

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.

首先,字符串开始的空白字符要跳过,并且需要记录首字母是‘+’‘-’或者直接就是数字,以此来判断正负数。
其次,对于转换结果,我们知道整型数据的范围是INT_MIN(-2147482648)到INT_MAX(2147483647),超出范围则返回最大与最小值。所以我们可以开始用long long类型的变量存储结果;
class Solution {
public:
    int myAtoi(string str) {
        if(str.size()==0)
            return 0;
        long long res=0;
        int flag=1;
        int i=0;
        while(str[i]==' ')
            i++;
        if(str[i]=='+')
            i++;
        else if(str[i]=='-'){
            flag=-1;
            i++;
        }
        for(int j=i;j<str.size();j++)
        {
            if(str[j]<='9'&&str[j]>='0')
            {    
                res=res*10+(str[j]-'0');
                if(res>INT_MAX)
                    return flag>0?INT_MAX:INT_MIN;
            }
            else
                break;
        }
        return res*flag;
    }
};


相关文章推荐

Leetcode 8. String to Integer (atoi)

Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases...

LeetCode 8:String to Integer (atoi)

Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases...

LeetCode OJ 8 String to Integer (atoi) [Medium]

题目描述: Implement atoi toconvert a string to an integer. Hint: Carefully consider all possible input...

leetcode: 8. String to Integer (atoi)

一. 题目描述:Implement atoi to convert a string to an integer.Hint: Carefully consider all possible input...

[LeetCode Java] 8 String to Integer (atoi)

/** * * Implement atoi to convert a string to an integer. * Hint: Carefully consider all possib...
  • ever223
  • ever223
  • 2015年03月13日 17:49
  • 442

leetcode8. String to Integer (atoi)

题目 Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input...

[LeetCode]8. String to Integer (atoi)

Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases...

[leetcode] 8. String to Integer (atoi) 解题报告

题目链接:https://leetcode.com/problems/string-to-integer-atoi/ Implement atoi to convert a string to a...

LeetCode 8. String to Integer (atoi)

很经典的一道面试题

Leetcode: 8. String to Integer (atoi)(JAVA)

【问题描述】 Implement atoi to convert a string to an integer. Hint: Carefully consider all possib...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode---(8)String to Integer (atoi)
举报原因:
原因补充:

(最多只允许输入30个字)