[Leetcode] String to Integer (atoi)

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] String to Integer (atoi)相关的知识,希望对你有一定的参考价值。

String to Integer (atoi) 题解

题目来源:https://leetcode.com/problems/string-to-integer-atoi/description/


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.

Solution


class Solution {
public:
    int myAtoi(string str) {
        int res = 0, i = 0;
        bool positive = true;
        while (str[i] == ‘ ‘) i++;
        if (str[i] == ‘-‘ || str[i] == ‘+‘) {
            positive = str[i] == ‘+‘;
            i++;
        }
        while (str[i] >= ‘0‘ && str[i] <= ‘9‘) {
            if (res > INT_MAX / 10 || (res == INT_MAX / 10 && str[i] - ‘0‘ > 7)) {
                return positive ? INT_MAX : INT_MIN;
            }
            res = res * 10 + (str[i] - ‘0‘);
            i++;
        }
        return positive ? res : -res;
    }
};

解题描述

这道题考察的是字符串转数字函数atoi的实现。最主要要解决的几个问题是:

  1. 忽略数字前面的空格
  2. 正负号判断
  3. 溢出判断
  4. 非法输入的判断

其中非法输入的判断在上面给出的解中是通过判断字符ASCII范围来判断的。

以上是关于[Leetcode] String to Integer (atoi)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 1055. Shortest Way to Form String

Leetcode: String to Integer (atoi)

[leetcode]String to Integer (atoi)

leetcode8 String to Integer

Leetcode008. String to Integer (atoi)

LeetCode String to Integer (atoi)