8. String to Integer (atoi)

官方的链接:8. String to Integer (atoi)

Description :

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.

问题描述

atoi (表示 ascii to integer)是把字符串转换成整型数的一个函数,函数会扫描参数nptr字符串,跳过前面的空白字符(例如空格)等,直到遇上数字或正负符号才开始做转换,而在遇到非数字或字符串结束时才结束转换,并将结果返回。如果 nptr不能转换成 int、nptr为空字符串,那么将返回 。溢出则返回INT_MAX或者INT_MIN。

思路

一开始理解有误,以为是各种字符都有。后来参考了下官网的Discuss,发现大致为:跳过空格,选择可选的前导+或者-,后面是尽可能多的数字,直到结束或者遇到非数字。以下的代码就当是一种参考。

项目中确实遇到过这种场景:数值型的字段使用正负号+定长字符,然后对字符串进行解析。 这种场景下会有正负号、符号后的0和实际的数字,比如定长10位,第1位是正负号:+066666660,实际上就是66666660。

[github-here]

 public class Q8_StringToInteger {
public int myAtoi(String str) {
if (null == str || str.isEmpty()) {
return 0;
}
int result = 0, sign = 1, index = 0, len = str.length();
while (index < len && str.charAt(index) == ' ') {
index++;
}
if (index == len) {
return 0;
}
if (str.charAt(index) == '+' || str.charAt(index) == '-') {
sign = str.charAt(index++) == '-' ? -1 : 1;
}
while (index < len && str.charAt(index) <= '9' && str.charAt(index) >= '0') {
//溢出判断
if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && str.charAt(index) - '0' > 7)) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
result = result * 10 + str.charAt(index++) - '0';
}
return result * sign;
}
}

Q8: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. No.008:String to Integer (atoi)

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

  3. 【leetcode】String to Integer (atoi)

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

  4. No.008 String to Integer (atoi)

    8. String to Integer (atoi) Total Accepted: 112863 Total Submissions: 825433 Difficulty: Easy Implem ...

  5. 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 ...

  6. Kotlin实现LeetCode算法题之String to Integer (atoi)

    题目String to Integer (atoi)(难度Medium) 大意是找出给定字串开头部分的整型数值,忽略开头的空格,注意符号,对超出Integer的数做取边界值处理. 方案1 class ...

  7. LeetCode--No.008 String to Integer (atoi)

    8. String to Integer (atoi) Total Accepted: 112863 Total Submissions: 825433 Difficulty: Easy Implem ...

  8. 《LeetBook》leetcode题解(8): String to Integer (atoi) [E]——正负号处理

    我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...

  9. 【Leet Code】String to Integer (atoi) ——常考类型题

    String to Integer (atoi) Total Accepted: 15482 Total Submissions: 106043My Submissions Implement ato ...

随机推荐

  1. dwr超时

    DWR可以指定超时设置: 1.设置局部超时: RemoteBean.remoteMethod(param1, param2, ..., { callback: callbackfun, //回调函数 ...

  2. 015.CI4框架CodeIgniter数据库操作之:Query带参数查询数

    01.我们在Models中写数据库的操作.具体的查询代码如下: <?php namespace App\Models\System; use CodeIgniter\Model; class U ...

  3. 获取控件的xy坐标

    procedure TForm1.SpeedButton1Click(Sender: TObject); var   Apoint:TPoint; begin   APoint:=TSpeedButt ...

  4. 使用Nginx搭建Tomcat9集群,Redis实现Session共享

    使用Nginx搭建Tomcat9集群,Redis实现Session共享 1.tomcat准备 首先准备两个tomcat9 ,修改配置文件server.xml 如果在多个服务器上分别启动tomcat 则 ...

  5. JS - 音频的播放和暂停

        $(".gameSound").bind("click",function() {             var audio = document.g ...

  6. 《Java面试全解析》1000道面试题大全详解(转)

    <Java面试全解析>1000道 面试题大全详解 本人是 2009 年参加编程工作的,一路上在技术公司摸爬滚打,前几年一直在上海,待过的公司有 360 和游久游戏,因为自己家庭的原因,放弃 ...

  7. 086-PHP数组按数字排序和按字母排序

    <?php $arr=array(2,54,167,'a','A','12'); //定义一个数组 echo '数组排序之前的信息:<br />'; print_r($arr); / ...

  8. Flink 历史服务与连接器

    History Server(历史服务) Flink提供了记录历史任务运行情况的服务,可用于在关闭Flink群集后依然能够查询已完成作业的相关信息. 配置: # 任务执行信息存储在hdfs目录 job ...

  9. python函数-迭代器&生成器

    python函数-迭代器&生成器 一.迭代器 1 可迭代协议 迭代:就是类似for循环,将某个数据集内的数据可以“一个挨着一个取出来” 可迭代协议: ① 协议内容:内部实现__iter__方法 ...

  10. VM安装CentOS7步骤

    VM15下载,在360软件管家就可以下载 CentOS7下载地址:http://mirror.bit.edu.cn/centos/7.6.1810/isos/x86_64/CentOS-7-x86_6 ...