首页 > 其他 > 详细

[LeetCode] String to Integer (atoi)

时间:2015-04-17 15:43:28      阅读:128      评论:0      收藏:0      [点我收藏+]

String to Integer (atoi)

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.

解题思路:

本身没有什么难度,需要弄清楚题意。比如,输入的字符一定是正确的整数格式吗?会不会溢出,若溢出如何处理?若有数字字符其他的字符如何处理?在面试中,可以向面试官问清楚这些,便可以动手写代码哒。我们可以先用一个long long类型来存储中间结果。

class Solution {
public:
    int myAtoi(string str) {
        int len = str.length();
        if(len==0){
            return 0;
        }
        int sign=1;
        int startIndex=0;
        while(str[startIndex]==' '){
            startIndex++;
        }
        if(str[startIndex]=='-'){
            startIndex++;
            sign=-1;
        }else if(str[startIndex]=='+'){
            startIndex++;
            sign=1;
        }
        long long tempResult=0;
        for(int i=startIndex; i<len; i++){
            if(str[i]<'0'||str[i]>'9'){
                break;
            }
            tempResult *= 10;
            tempResult += str[i]-'0';
            if(tempResult>2147483647){
                break;
            }
        }
        tempResult *= sign;
        int result = (int)tempResult;
        if(result!=tempResult){
            if(sign<0){
                result=-2147483648;
            }else{
                result=2147483647;
            }
        }
        return result;
    }
};


[LeetCode] String to Integer (atoi)

原文:http://blog.csdn.net/kangrydotnet/article/details/45096775

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!