LeetCode-008 String to Integer (atoi)

来源:互联网 发布:淘宝的聚划算怎么抢 编辑:程序博客网 时间:2024/06/05 06:54

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.

Analyse

题目很简单,就是让你把一个字符串转换为一个整型。题目越简单,出问题的几率越大,题目几乎什么都没说,连测试样例都没有给,根本有哪几种不合法的输入,被坑了若干遍之后,发现了这道题的所有的坑点。。。
(1)无视前面空格,若后面开始输入数字之后出现空格,直接终止算法,坑点。
(2)符号有‘+’和‘-’但是需要注意的是,符号只能出现一遍,若出现第二遍的话,直接终止算法,这是一个很大的坑点。
(3)若整数越界,则返回最接近该整数的边界,即最大32位整数或最小32位整数。
把上面三个问题处理妥当之后,这道题就很简单了,我在上面的坑浪费了很多的时间。

Code

class Solution {public:    int myAtoi(string str) {        int len=str.length();        int sign=1;//符号        long num=0;        bool flag=false;//用来判断符号是否第一次出现        int i=0;        while (i<len && str[i]==' ') i++;//去除前置空格        for (;i<len;i++) {            if (str[i]=='-' && !flag) sign=-sign;            if (str[i]>='0' && str[i]<='9') {                num=num*10+(str[i]-'0');                if (sign*num>INT_MAX) return INT_MAX;                if (sign*num<INT_MIN) return INT_MIN;            } else {                if ((str[i]=='+' || str[i]=='-') && !flag) {                    flag=true;                } else break;            }        }        return (int) sign*num;    }};