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

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

description:

Implement atoi which converts a string to an integer.

实现string转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.
这个功能首先要去掉在string前面的空格,如果第一个非空的字符是正负号,则要做一个标记,在他的后边要找到尽可能多的数字,然后都转成整形类型。

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.

如果第一个字符既不是正负号也不是数字就stop

If no valid conversion could be performed, a zero value is returned.

Example 1:Input: "42"Output: 42Example 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.

my answer:

class Solution {public:    int myAtoi(string str) {        if (str.empty()) return 0; //要考虑string为空的情况        int base = 0, sign = 1, i = 0, n = str.size();        while(i < n && str[i] == ' ') ++i; // i
= '0' && str[i] <= '9'){ if(base > INT_MAX/10 || (base == INT_MAX/10 && str[i] - '0' > 7)){ return (sign == 1) ? INT_MAX : INT_MIN; } base = base * 10 + (str[i++] - '0'); } return sign * base; }};

relative point get√:

在while循环里还想实现for循环的i++,可以在while的代码段里调用i的时候就用i++,如上面代码里的str[i++]

hint :

关键在于数清可能遇到的可能情况

转载于:https://www.cnblogs.com/forPrometheus-jun/p/10572178.html

你可能感兴趣的文章
Android SQLite服务--创建、增删改查
查看>>
建造者模式 生成器模式 创建型 设计模式(五)
查看>>
《人月神话》读书笔记之第1章焦油坑
查看>>
Effective Objective-C 2.0 Tips 总结 Chapter 3 & Chapter 4
查看>>
留学生题目
查看>>
pythoon介绍、安装环境、基础知识、练习题
查看>>
水溶彩铅的特点&技法运用
查看>>
vue使用laydate.js插件报错laydate.css: Invalid
查看>>
Odoo 强大的开源微信模块 oejia_wx
查看>>
批量创建邮箱通讯组及向通讯组批量添加成员
查看>>
参加51CTO学院软考培训,我通过啦!
查看>>
resharper 7.x 注册码key
查看>>
tomcat的安装以及配置
查看>>
ansible之cron模块
查看>>
ngx_lua 模块提供的指令和API等
查看>>
GHOSTXPSP3系统封装网页图文教程
查看>>
第26讲 python文件的格式化写入
查看>>
Jquery 常用
查看>>
ACL in 和 out
查看>>
从零起步到Linux运维经理,你必须管好的23个细节
查看>>