题目

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.

spoilers alert... click to show requirements for atoi.

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.

题解

这题主要就是考虑一下corner case。

越界问题?

正负号问题?

空格问题?

精度问题?

代码如下:

 1    public int atoi(String str) {
 2     if (str == null || str.length() < 1)
 3         return 0;
 4  
 5     // trim white spaces
 6     str = str.trim();
 7  
 8     char flag = '+';
 9  
10     // check negative or positive
11     int i = 0;
12     if (str.charAt(0) == '-') {
13         flag = '-';
14         i++;
15     } else if (str.charAt(0) == '+') {
16         i++;
17     }
18     // use double to store result
19     double result = 0;
20  
21     // calculate value
22     while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
23         result = result * 10 + (str.charAt(i) - '0');
24         i++;
25     }
26  
27     if (flag == '-')
28         result = -result;
29  
30     // handle max and min
31     if (result > Integer.MAX_VALUE)
32         return Integer.MAX_VALUE;
33  
34     if (result < Integer.MIN_VALUE)
35         return Integer.MIN_VALUE;
36  
37     return (int) result;
38 }

更新:

因为遇见过了atol,string to long 这样的问题,就不能用这种比当前数据类型长的方法解决。

另一种方法是更加普遍和巧妙的,就是用这样的判断:

1. Integer.MAX_VALUE/10 < result; //当前转换结果比Integer中最大值/10还大(因为这个判断放在while循环最开始,之后还要对result进行*10+当前遍历元素的操作,所以如果还乘10的result已经比Integer.MAX_VALUE/10还大,可想而知,乘了10更大)

2. Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE%10 <(str.charAt(i) - '0') //另外的情况就是,当前result恰跟 Integer.MAX_VALUE/10相等,那么就判断当前遍历的元素值跟最大值的最后一位的大小关系即可

代码如下:

 1   public int atoi(String str) {
 2     if (str == null || str.length() < 1)
 3         return 0;
 4  
 5     // trim white spaces at beginning and end
 6     str = str.trim();
 7  
 8     char flag = '+';
 9  
10     // check negative or positive
11     int i = 0;
12     if (str.charAt(0) == '-') {
13         flag = '-';
14         i++;
15     } else if (str.charAt(0) == '+') {
16         i++;
17     }
18     // use double to store result
19     int result = 0;
20  
21     // calculate value
22     while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
23         if(Integer.MAX_VALUE/10 < result || (Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE%10 < (str.charAt(i) - '0'))) 
24             return flag == '-' ? Integer.MIN_VALUE : Integer.MAX_VALUE;
25             
26         result = result * 10 + (str.charAt(i) - '0');
27         i++;
28     }
29  
30     if (flag == '-')
31         result = -result;
32  
33     return result;
34 }

Reference: http://www.programcreek.com/2012/12/leetcode-string-to-integer-atoi/

String to Integer (atoi) leetcode java相关推荐

  1. 008 String to Integer (atoi) [Leetcode]

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

  2. LeetCode算法入门- String to Integer (atoi)-day7

    LeetCode算法入门- String to Integer (atoi)-day7 String to Integer (atoi): Implement atoi which converts ...

  3. 【细节实现题】LeetCode 8. String to Integer (atoi)

    LeetCode 8. String to Integer (atoi) Solution1:我的答案 参考链接:http://www.cnblogs.com/grandyang/p/4125537. ...

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

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

  5. LeetCode 8. String to Integer (atoi)(字符串)

    LeetCode 8. String to Integer (atoi)(字符串) LeetCode 8 String to Integer atoi字符串 问题描述 解题思路 参考代码 By Sca ...

  6. [LeetCode] NO. 8 String to Integer (atoi)

    [题目] Implement atoi to convert a string to an integer. [题目解析] 该题目比较常见,从LeetCode上看代码通过率却只有13.7%,于是编码提 ...

  7. leetcode 8. String to Integer (atoi)

    也许是我没有理解清楚题意,为什么输入+-2的时候要输出0,而不是输出2呢. public class Solution {public int myAtoi(String str) {if(str = ...

  8. 8. String to Integer (atoi)

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

  9. Leet Code OJ 8. String to Integer (atoi) [Difficulty: Easy]

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

最新文章

  1. 【知识必备】浅淡MVP在Android项目中的实战演习,让代码结构更简单~
  2. 【云ERP】SAP S/4 HANA CLOUD 采购订单处理基本操作
  3. RxSwift 系列(一)
  4. arduino neo 定位不可用_arduino霹雳七彩灯
  5. delphi 关闭时缩小到托盘_如何正确地缩小毛孔?
  6. java 生成uuid
  7. 免费提供离线地图部署服务
  8. 有人称2022年将会是DAO的元年
  9. might和could的区别用法_could might would should区别用法
  10. 成长之路——发现问题、提出问题和解决问题
  11. 区块链十年一梦:有人辞官归故里,有人星夜来赶考
  12. 7天带你搞定一个图表框架echarts(六)
  13. 好看的黑色响应式滚动式动态背景个人导航HTML源码
  14. 安装SQL server出现“服务没有及时响应启动或控制请求”
  15. python中cv是什么_python里面cv是什么意思
  16. 数字图像处理 彩色图象处理
  17. 富士康14跳被我赶上了,流水线车间真的没有梦想|十年系列
  18. Python文字(汉字)转语音https://zhuanlan.zhihu.com/p/26726297
  19. php微信支付结果通知接收,浅析PHP微信支付通知的处理方式
  20. python闲鱼机器人_自动化篇 - 躺着收钱!闲鱼自动发货机器人来啦~

热门文章

  1. Android-可自动缩小字体的TextView
  2. C语言-二维数组做函数的参数
  3. 【Android Gradle 插件】Module 目录下 build.gradle 配置文件 ( plugins 闭包代码块中引入插件 | PluginAware#apply 方法引入插件 )
  4. 【C 语言】结构体 ( 结构体中嵌套二级指针 | 为 结构体内的二级指针成员 分配内存 | 释放 结构体内的二级指针成员 内存 )
  5. 【C 语言】const 关键字用法 ( 常量指针 - const 在 * 左边 - 修饰数据类型 - 内存不变 | 指针常量 - const 在 * 右边 - 修饰变量 - 指针不变 )
  6. 【Android 逆向】函数拦截实例 ( ② 插桩操作 | 保存实际函数入口 6 字节数据 | 在插桩的函数入口写入跳转指令 | 构造拼接桩函数 )
  7. 【Android 逆向】Android 逆向通用工具开发 ( 网络模块开发 | SOCKET 网络套接字初始化 | 读取远程端 “Android 模拟器“ 信息 | 向远程端写出数据 )
  8. 【字符串】最长回文子串 ( 动态规划算法 ) ★
  9. 【计算理论】计算理论总结 ( 下推自动机计算过程 | 上下文无关文法 CFG 转为下推自动机 PDA ) ★★
  10. 【Android 高性能音频】Oboe 开发流程 ( 导入 Oboe 库 | 使用预构建的二进制库和头文件 | 编译 Oboe 源码 )