博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] String to Integer (atoi)
阅读量:4556 次
发布时间:2019-06-08

本文共 3126 字,大约阅读时间需要 10 分钟。

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.

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.

class Solution {public:    int atoi(const char *str) {        if(str == NULL || str[0] == '\0') return 0;        int cur = 0, sign = 0, loc = 0;        while(str[loc] == ' ')            loc++;        if(str[loc] == '-')         {            sign = -1;            loc++;        }        else if(str[loc] == '+')        {            sign = 1;            loc++;        }        else            sign = 1;        while(str[loc] != '\0' && str[loc] >= '0' && str[loc] <= '9')        {            int tmp = cur;            cur = cur * 10 + str[loc++] - '0';            bool flag = ((cur - str[loc - 1] + '0') / 10) == tmp && cur >= 0; //这里判断溢出的方法不合理            if(!flag && sign == 1)                return INT_MAX;            else if(!flag && sign == -1)                return INT_MIN;        }        return cur * sign;    }}; //此题对于溢出的处理可以有两种思路,一种是用long long来存运算结果,防止溢出 //另外一种是在溢出可能发生前加以判断,代码如下
class Solution { public:     int atoi(const char *str) {         // Start typing your C/C++ solution below         // DO NOT write int main() function         assert(str != NULL);                  while(isspace(*str)) str++;  // remove ' '                                   int sign = (*str == '-') ? -1 : 1;                  if (*str == '-' || *str == '+')    // if can check one char             str++;                      int ret = 0;         while(isdigit(*str))   // is digit         {             int digit = *str - '0';                          if (INT_MAX / 10 >= ret)                 ret *= 10;             else                 return sign == -1 ? INT_MIN : INT_MAX;                              if (INT_MAX - digit >= ret)                 ret += digit;             else                 return sign == -1 ? INT_MIN : INT_MAX;                              str++;         }                  return ret * sign;     } };
 

转载于:https://www.cnblogs.com/changchengxiao/p/3639371.html

你可能感兴趣的文章
下载特定区域内街景照片数据 | Download Street View Photos within Selected Region
查看>>
StarUML 破解方法
查看>>
C语言结构体
查看>>
[转]Tribon船体生产设计应用
查看>>
easy ui datagrid 让某行复选框不能选中
查看>>
第六周作业
查看>>
关于adb端口被占用的解决办法
查看>>
php 部分内置函数的使用
查看>>
字符串处理技巧
查看>>
归档及压缩命令
查看>>
Mybatis步骤
查看>>
WPF自定义控件之扩展原生控件
查看>>
《区块链100问》笔记整理——42~49问
查看>>
使用Jquery+EasyUI 进行框架项目开发案例讲解之二---用户管理源码分享
查看>>
深入理解计算机系统(1.4)---并发与并行、浅谈抽象
查看>>
函数依赖的公理化系统
查看>>
rabbitmq学习(四):利用rabbitmq实现远程rpc调用
查看>>
侯捷C++学习(二)
查看>>
EasyPlayer RTSP Android安卓播放器修复播放画面卡在第一帧bug
查看>>
web项目中全局常量的添加
查看>>