LeetCode—8. String to Integer (atoi)

Type:medium

Implement atoi which converts a string to an integer.

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.

Note:

Only the space character ' ' is considered as whitespace character.

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1:

Input:"42"Output:42

Example 2:

Input:"  -42"Output:-42Explanation:The first non-whitespace character is '-', which is the minus sign.             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input:"4193 with words"Output:4193Explanation:Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input:"words and 987"Output:0Explanation:The first non-whitespace character is 'w', which is not a numerical              digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input:"-91283472332"Output:-2147483648Explanation:The number "-91283472332" is out of the range of a 32-bit signed integer.             Thefore INT_MIN (−231) is returned.


题干很长,但总结来说,就是把string型转化为int型,其中有几个要点:

1、若是string前几位都是' ',则一直往后读到非空格位

2、若第一个非空格位为'+'或'-',则记录为该数的正负

3、若遇到非数字位,则返回之前读到的有效位;在已经读取到'+'或'-'的情况下,同理

4、若超过int范围,返回边界值

于是首先读取第一个非空格位,这里可以用自带函数i =str.find_first_not_of(' ')直接跳到第一个非空格位,我的代码里则是用while语句读取。

定义符号位sign以及上一个有效值base。

继续读取string字符串,若遇到非数字位,则break。若是数字位,则判断该值是否超出边界,若不超出边界,base = 10 * base + (str[i] - '0')。最后返回加上符号位的base。

本题并不难,但要掌握INT_MAX以及INT_MIN的值,并要注意读数不要超出边界。另外别忘了给sign赋初值!!!


class Solution {

public:

    int myAtoi(string str) {

        int n=str.length();

        if(n == 0) return 0;

        int sign = 1;

        int base = 0;

        int j=0;

        while(str[j] == ' ' && j<n){

            j++;

        }

        if(str[j] == '+' && j<n) {

            sign = 1;

            j++;

        }else if(str[j] == '-' && j<n){

            sign = -1;

            j++;

        }

        for(int i=j; i<n; i++){ 

            if(str[i] <= '9' && str[i] >= '0'){

                if((base == INT_MAX/10 && str[i] >= '7' && sign == 1)|| (base == INT_MAX/10 && str[i] >= '8' && sign == -1 )){

                    return (sign==1)?  INT_MAX:INT_MIN;

                }else if(base > INT_MAX/10){

                    return (sign==1)?  INT_MAX:INT_MIN;

                }

                base = 10 * base + (str[i] - '0');

            }else break;

        }

        if(base != 0) return sign * base;

        return 0;

    }

};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容