一.题目链接:https://leetcode.com/problems/string-to-integer-atoi/

二.题目大意:

  实现一个和C语言里atoi具有相同功能的函数,即能够把字符串转换成整型。例如:输入字符串“-123”,返回值为一个整数-123。

三.题解:

  这道题也属于字符串处理类的题目,只要看懂题目所给定的规则就好了,题目给的规则大致如下:

1.若一开始遇到连续的2空白字符,则忽略这些字符,直到遇到第一个非空白字符。

2.若遇到的第一个空白字符为'+'或者'-',则只有下一个字符为数字字符时才继续执行,否则返回0。如果下一个字符为数字字符,那么就往后顺序判断字符是否为数字字符,直到遇到非数字字符(然后该字符之后的字符串就不用考虑了)。

3.若遇到的第一个非空白字符为数字字符,则执行与第2步相同的操作,即往后顺序判断字符是否为数字字符,直到遇到非数字字符(然后该字符之后的字符串就不用考虑了)。(实际上相当于第一个出现的数字字符串)

4.如果数字字符串转换成的数字大于INT_MAX(int所能表示的最大值),或者小于INT_MIN(int所能表示的最小值)的话,则返回INT_MAX或者INT_MIN。

这里有需要注意的一点是:这道题不用考虑小数的问题,因为题目要求转化的是整型,不包括浮点型!!!

看懂这道题目给定的规则后,实现就简单了,代码如下:

class Solution
{
public:
int myAtoi(string str)
{
int len = str.size();
long long rs = 0;
int i = 0;
int flag = 1;//表示正负号
while(i < len && str[i] == 32)
{
i++;
}
if(str[i] == '+')
{
flag = 1;
i++;
while(str[i] >= '0' && str[i] <= '9')
{
rs = rs * 10 + str[i] - '0';
i++;
if(rs > INT_MAX)
break;
} }
else if(str[i] == '-')
{
flag = -1;
i++;
while(str[i] >= '0' && str[i] <= '9')
{
rs = rs * 10 + str[i] - '0';
i++;
if(rs > INT_MAX)
break;
}
}
else if(str[i] >= '0' && str[i] <= '9')
{
while(str[i] >= '0' && str[i] <= '9')
{
rs = rs * 10 + str[i] - '0';
i++;
if(rs > INT_MAX)
break;
}
}
else
return 0;
rs = rs *flag;
if(rs > INT_MAX)
return INT_MAX;
else if(rs < INT_MIN)
return INT_MIN;
else
return rs;
} };

 该算法的时间复杂度为O(n),空间复杂度为O(1),这段代码有几处需要重点理解:

1.字符转数字的操作为:rs = rs * 10 + str[i] - '0'。此处实际上与第7题反转数字(http://www.cnblogs.com/wangkundentisy/p/8059028.html)用了相同的道理,这么做的好处是不用事先知道字符串的长度。

2.在while循环中有一步为:if(rs > INT_MAX)  break;为什么要加这一步?最后的判断不能的代替这一步吗?

确实不能,因为rs 是long long型,这种数据类型占8个字节,它表示的范围也是有限的,所以当超过这个范围时,就会发生溢出,产生错误的返回值(例如:“1212121212121212121212121212121212121212”)。所以在字符串转化的过程中,一旦发现超过int的范围,就终止,就不会发生这种情况了。(之前我想的是把所有的rs都加完之后再考虑,这样就有可能发生上述情况,所以在rs增加的过程中判断才是比较合理的)。

LeetCode——8. String to Integer (atoi)的更多相关文章

  1. Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串)

    Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串) 题目描述 实现atoi函数,将一个字符串转化为数字 测试样例 Input: "42&q ...

  2. leetcode day6 -- String to Integer (atoi) &amp;&amp; Best Time to Buy and Sell Stock I II III

    1.  String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully con ...

  3. 【leetcode】String to Integer (atoi)

    String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...

  4. [leetcode] 8. String to Integer (atoi) (Medium)

    实现字符串转整形数字 遵循几个规则: 1. 函数首先丢弃尽可能多的空格字符,直到找到第一个非空格字符. 2. 此时取初始加号或减号. 3. 后面跟着尽可能多的数字,并将它们解释为一个数值. 4. 字符 ...

  5. Leetcode 8. String to Integer (atoi)(模拟题,水)

    8. String to Integer (atoi) Medium Implement atoi which converts a string to an integer. The functio ...

  6. [LeetCode][Python]String to Integer (atoi)

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/string- ...

  7. 【LeetCode】String to Integer (atoi) 解题报告

    这道题在LeetCode OJ上难道属于Easy.可是通过率却比較低,究其原因是须要考虑的情况比較低,非常少有人一遍过吧. [题目] Implement atoi to convert a strin ...

  8. LeetCode 8. String to Integer (atoi) (字符串到整数)

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

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

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

  10. LeetCode 7 -- String to Integer (atoi)

    Implement atoi to convert a string to an integer. 转换很简单,唯一的难点在于需要开率各种输入情况,例如空字符串,含有空格,字母等等. 另外需在写的时候 ...

随机推荐

  1. 基于hiredis,redis C客户端封装

    项目中需要用到redis就封装了一下,基于hiredis,只封装了string和哈希的部分方法.编译时加入-D__USER_LOCK__添加线程安全. suntelRedisCli.h #ifndef ...

  2. nginx根据url中的参数进行转发

    在实际项目中,由于https安全策略,我们无法直接跳转到我们想要跳转到的地址 例如 url:https://abc.dc.com/image?url=https://vpic.video.qq.com ...

  3. map遍历的几种方式和效率问题

    一.map遍历的效率 先创建一个map,添加好数据: Map<String, String> map = new HashMap<>();for (int i = 0; i & ...

  4. Go Example--Hello

    Hello world package main import "fmt" //通过import导入fmt标准包 func main() { //语句结尾不需要;分号, //Pri ...

  5. CH3B16 魔法珠

    题意 3B16 魔法珠 0x3B「数学知识」练习 描述 Freda和rainbow是超自然之界学校(Preternatural Kingdom University,简称PKU)魔法学院的学生.为了展 ...

  6. c# 自定义log4net过滤器

    有时候为了实现自己想要的多个日志文件记录不同的内容,可能需要自定义log4net过滤器,比如我这里需要记录三个文件,这三个文件的内容又不能重复,多次尝试未果. 为了不更改任何现有日志代码的情况下,于是 ...

  7. Yocto学习笔记

    1. 指定SRCREV的例子 #kernel-module-m8887-wlan.bb DESCRIPTION = "Marvell M8887 Wifi kernel module&quo ...

  8. skipper backend 负载均衡配置

    skipper 对于后端是支持负载均衡处理的,支持官方文档并没有提供,实际使用中,这个还是比较重要的 同时支持健康检查. 格式 hello_lb_group: Path("/foo" ...

  9. css3新增内容

    1.css3边框 border-radius box-shadow border-image 2.背景 background-size background-origin 3.文本效果 text-sh ...

  10. Java IO的一些列子

    Write()方法写入文件 public static void main(String[] args){ try{ BufferedWriter out = new BufferedWriter(n ...