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:

  1. Input: "42"
  2. Output: 42

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

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

字符串转为整数是很常用的一个函数,由于输入的是字符串,所以需要考虑的情况有很多种。博主之前有一篇文章是关于验证一个字符串是否为数字的,参见 Valid Number。在那篇文章中,详细的讨论了各种情况,包括符号,自然数,小数点的出现位置,判断他们是否是数字。个人以为这道题也应该有这么多种情况。但是这题只需要考虑数字和符号的情况:

1. 若字符串开头是空格,则跳过所有空格,到第一个非空格字符,如果没有,则返回0.

2. 若第一个非空格字符是符号 +/-,则标记 sign 的真假,这道题还有个局限性,那就是在 c++ 里面,+-1 和-+1 都是认可的,都是 -1,而在此题里,则会返回0.

3. 若下一个字符不是数字,则返回0,完全不考虑小数点和自然数的情况,不过这样也好,起码省事了不少。

4. 如果下一个字符是数字,则转为整形存下来,若接下来再有非数字出现,则返回目前的结果。

5. 还需要考虑边界问题,如果超过了整型数的范围,则用边界值替代当前值。

C++ 解法:

  1. class Solution {
  2. public:
  3. int myAtoi(string str) {
  4. if (str.empty()) return ;
  5. int sign = , base = , i = , n = str.size();
  6. while (i < n && str[i] == ' ') ++i;
  7. if (i < n && (str[i] == '+' || str[i] == '-')) {
  8. sign = (str[i++] == '+') ? : -;
  9. }
  10. while (i < n && str[i] >= '' && str[i] <= '') {
  11. if (base > INT_MAX / || (base == INT_MAX / && str[i] - '' > )) {
  12. return (sign == ) ? INT_MAX : INT_MIN;
  13. }
  14. base = * base + (str[i++] - '');
  15. }
  16. return base * sign;
  17. }
  18. };

Java 解法:

  1. public class Solution {
  2. public int myAtoi(String str) {
  3. if (str.isEmpty()) return ;
  4. int sign = , base = , i = , n = str.length();
  5. while (i < n && str.charAt(i) == ' ') ++i;
  6. if (i < n && (str.charAt(i) == '+' || str.charAt(i) == '-')) {
  7. sign = (str.charAt(i++) == '+') ? : -;
  8. }
  9. while (i < n && str.charAt(i) >= '' && str.charAt(i) <= '') {
  10. if (base > Integer.MAX_VALUE / || (base == Integer.MAX_VALUE / && str.charAt(i) - '' > )) {
  11. return (sign == ) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
  12. }
  13. base = * base + (str.charAt(i++) - '');
  14. }
  15. return base * sign;
  16. }
  17. }

Github 同步地址:

https://github.com/grandyang/leetcode/issues/8

类似题目:

Reverse Integer

Valid Number

参考资料:

https://leetcode.com/problems/string-to-integer-atoi/

https://leetcode.com/problems/string-to-integer-atoi/discuss/4654/My-simple-solution

https://leetcode.com/problems/string-to-integer-atoi/discuss/4642/8ms-C%2B%2B-solution-easy-to-understand

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] String to Integer (atoi) 字符串转为整数的更多相关文章

  1. [LeetCode] 8. String to Integer (atoi) 字符串转为整数

    Implement atoi which converts a string to an integer. The function first discards as many whitespace ...

  2. Leetcode8.String to Integer (atoi)字符串转整数(atoi)

    实现 atoi,将字符串转为整数. 该函数首先根据需要丢弃任意多的空格字符,直到找到第一个非空格字符为止.如果第一个非空字符是正号或负号,选取该符号,并将其与后面尽可能多的连续的数字组合起来,这部分字 ...

  3. String to Integer (atoi) - 字符串转为整形,atoi 函数(Java )

    String to Integer (atoi) Implement atoi to convert a string to an integer. [函数说明]atoi() 函数会扫描 str 字符 ...

  4. 【LeetCode】8. String to Integer (atoi) 字符串转换整数

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:字符串转整数,atoi,题解,Leetcode, 力扣,P ...

  5. [leetcode]8. String to Integer (atoi)字符串转整数

    Implement atoi which converts a string to an integer. The function first discards as many whitespace ...

  6. [Leetcode] String to integer atoi 字符串转换成整数

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

  7. 【LeetCode】String to Integer (atoi)(字符串转换整数 (atoi))

    这道题是LeetCode里的第8道题. 题目要求: 请你来实现一个 atoi 函数,使其能将字符串转换成整数. 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止. 当我们 ...

  8. 【LeetCode】8. String to Integer (atoi) 字符串转整数

    题目: Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input ca ...

  9. 008 String to Integer (atoi) 字符串转换为整数

    详见:https://leetcode.com/problems/string-to-integer-atoi/description/ 实现语言:Java class Solution { publ ...

随机推荐

  1. 基于 HTML5 的 Web SCADA 报表

    背景 最近在一个 SCADA 项目中遇到了在 Web 页面中展示设备报表的需求.一个完整的报表,一般包含了筛选操作区.表格.Chart.展板等多种元素,而其中的数据表格是最常用的控件.在以往的工业项目 ...

  2. 结合ABP源码实现邮件发送功能

    1. 前言 2. 实现过程 1. 代码图(重) 2.具体实现 2.1 定义AppSettingNames及AppSettingProvider 2.2 EmailSenderConfiguration ...

  3. 简单实用的进度条加载组件loader.js

    本文提供一个简单的方法实现一个流程的进度条加载效果,以便在页面中可以通过它来更好地反馈耗时任务的完成进度.要实现这个功能,首先要考虑怎样实现一个静态的进度条效果,类似下面这样的: 这个倒是比较简单,两 ...

  4. C# async/await 使用总结

    今天搞这两个关键字搞得有点晕,主要还是没有彻底理解其中的原理. 混淆了一个调用异步方法的概念: 在调用异步方法时,虽然方法返回一个 Task,但是其中的代码已经开始执行.该方法在调用时,即刻执行了一部 ...

  5. 『.NET Core CLI工具文档』(九)dotnet-run

    说明:本文是个人翻译文章,由于个人水平有限,有不对的地方请大家帮忙更正. 原文:dotnet-run 翻译:dotnet-run 名称 dotnet-run -- 没有任何明确的编译或启动命令运行&q ...

  6. 使用nvm利器,管理node版本

    node.js越来越热,应用的场景也越来越多. 但也因为是开源软件,所以具备大多数开源软件都存在的“版本问题”,版本发展很快,版本前后差异性大,老系统用新版本node跑不过,全局安装的第三方组件和no ...

  7. poj1698--最大流(Dinic)

    题目大意: 爱丽丝要拍电影,有n部电影,规定爱丽丝每天只能拍一部电影,每部电影在每个礼拜只有固定的几天可以拍电影,只可以拍前面w个礼拜,并且这部电影要拍d天,问爱丽丝能不能拍完所有的电影. 思路: 建 ...

  8. css设置table表格tr分离

    table { border-collapse:separate; border-spacing:10px 50px; }

  9. JavaWeb_day05cookie_session_HttpSession

    本文为博主辛苦总结,希望自己以后返回来看的时候理解更深刻,也希望可以起到帮助初学者的作用. 转载请注明 出自 : luogg的博客园 谢谢配合! 两个会话的技术cookie session 会话概念 ...

  10. 用C++实现的贪吃蛇游戏

    我是一个C++初学者,控制台实现了一个贪吃蛇游戏. 代码如下: //"贪吃蛇游戏"V1.0 //李国良于2016年12月29日编写完成 #include <iostream& ...