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] 8. String to Integer (atoi) 字符串转为整数的更多相关文章

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  8. Leetcode 8 String to Integer (atoi) 字符串处理

    题意:将字符串转化成数字. 前置有空格,同时有正负号,数字有可能会溢出,这里用long long解决(leetcode用的是g++编译器),这题还是很有难度的. class Solution { pu ...

  9. LeetCode OJ String to Integer (atoi) 字符串转数字

    #include <iostream> #include <assert.h> using namespace std; int ato(const char *str) { ...

随机推荐

  1. JVM的监控工具之jstack

    参考博客:https://www.jianshu.com/p/213710fb9e40 jstack(Stack Trace for Java)命令用于生成虚拟机当前时刻的线程快照(一般称为threa ...

  2. kali渗透综合靶机(五)--zico2靶机

    kali渗透综合靶机(五)--zico2靶机 靶机地址:https://www.vulnhub.com/series/zico2,137/#modal210download 一.主机发现 1.netd ...

  3. kafka中消费者消费消息之每个线程维护一个KafkaConsumer实例

    1.首先启动自己的kafka集群哟. 启动zk: bin/zkServer.sh start conf/zoo.cfg. 验证zk是否启动成功: bin/zkServer.sh status conf ...

  4. VS2019打开旧项目导致引用失效的解决方案

    用VS2019打开VS2015创建的MVC项目时所有引用全部失效: 解决方案: 打开项目的csproj文件,删除 Target节点,在重新打开项目. <Target Name="Ens ...

  5. C 数组、枚举类型enum

    传递数组给函数 告诉编译器函数要接受一个指针 skip //函数声明,数组的长度无需声明,因为编译器不会对形式参数进行边界检查 void myFunction(int param[]) //或者 vo ...

  6. Java面向对象——类的成员

    Java面向对象——类的成员 摘要:本文主要介绍了类的常见成员. 属性 属性称为成员变量,一般来讲不用赋值,因为有默认值,另外显式赋值没有意义会导致所有由此类创建对象都是此值. 默认值 Boolean ...

  7. Eureka获取服务列表源码解析

    在之前的文章:EurekaClient自动装配及启动流程解析中,我们提到了在类DiscoveryClient的构造方法中存在一个刷新线程和从服务端拉取注册信息的操作 这两个就是eureka获取服务列表 ...

  8. skipped obstructing working copy

    svn update时报错,处理方法,将报错的文件夹压缩备份一下,然后删除报错的文件夹,重新update即可.

  9. 使用python来反查数据表中的字段名

    1. 链接数据库 import psycopg2 conn = psycopg2.connect(user,host,port,database,password) cur = conn.cursor ...

  10. [PHP] 使用ftell和fseek函数直接定位文件位置获取部分数据

    对于大文件只获取部分数据很有用 1.使用ftell函数可以获取当前指针的字节位置2.使用fseek函数可以直接定位到指定的位置3.读取指定字节的数据就可以部分获取文件内容了 <?php clas ...