码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] String to Integer (atoi)

时间:2018-01-25 11:05:54      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:string   函数   hat   asc   put   ems   rem   source   ascii   

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)

标签:string   函数   hat   asc   put   ems   rem   source   ascii   

原文地址:https://www.cnblogs.com/yanhewu/p/8349755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!