[LeetCode]#8 String to Integer (atoi)

来源:互联网 发布:淘宝客发单机器人 编辑:程序博客网 时间:2024/06/05 21:04

GitHub : https://github.com/MummyDing/LeetCode

Source : https://leetcode.com/problems/string-to-integer-atoi/

Description :

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.


题解: 题目意思就是以字符串的形式给你一个整数,要你转换成整型返回,但是这个字符串中可能会有一些其他奇奇怪怪的符号.这在题目的开头已经提示了叫我们考虑多种情况,最好不要看提示,然后我就很听话的没有看提示 了,自然而然地wrong了好多发.根据一次次的错误数据也把它的转换规则搞清楚了,有点坑... 我的做法是首先将字符串进行一次预处理,将"真正的数字"部分抠出来,然后判断正负,看其是否超出整型范围,超出直接根据要求返回(题目中有说明,虽然我没有看,但是wrong了两发就知道了---囧--).最后如果没有超出范围那就很简单直接转换了. 其实这题用Java写也挺好,不过题目也并不复杂,就C++算了.最后运行时间是12ms,绝大部分的都是这样.


/*Problem: String to Integer (atoi)Description: https://leetcode.com/problems/string-to-integer-atoi/Author: MummyDingDate : 2015-12-29Run Time: 12 ms*/#include <iostream>using namespace std;class Solution {public:    int myAtoi(string str) {            //filter the number            int len = str.size(),startX=-1,endX = -1;            bool sign = true;            for(int i=0 ; i<len ; i++){                if(startX == -1){                    if(str[i] == ' ') continue;                    if(str[i] == '+' || str[i] == '-'  || str[i]>='0' && str[i]<='9'){                        startX = i;                    }else {                        return 0;                    }                }else if((str[i]>='0' && str[i]<='9') == false){                    endX = i;                    break;                }                if(endX == -1 && len-1 == i){                        endX = i+1;                }            }            if(startX == -1 || endX == -1) return 0;            //cout<<str.substr(startX,endX-startX)<<endl;            if(str[startX] == '-'){                sign = false;                startX++;            }else if(str[startX] == '+'){                startX++;            }            string res = str.substr(startX,endX-startX);            int lenR = res.size() , resNum = 0, pow = 1;            // int  -2147483648 ~ 2147483647            if(sign && (res>"2147483647" && lenR ==10 || lenR>10)){                return 2147483647;            }else if(sign ==false && res >"2147483648" && lenR ==10 || lenR>10){               return  -2147483648;            }            // convert string to num            for(int i = lenR-1 ; i>=0 ; i--){                resNum += ((res[i]-'0')*pow);                pow *=10;            }            if(sign) return resNum;            else return -resNum;    }};int main(){   // Solution s;   // cout<<s.myAtoi(" 444-11228552307")<<endl;    return 0;}

【转载请注明出处】

Author: MummyDing

出处:http://blog.csdn.net/u012560612/article/category/6047025


0 0
原创粉丝点击