题目

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  
     // check negative or positive
     int i = 0;
     if (str.charAt(0) == '-') {
         flag = '-';
         i++;
     } else if (str.charAt(0) == '+') {
         i++;
     }
     // use double to store result
     double result = 0;
  
     // calculate value
     while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
         result = result * 10 + (str.charAt(i) - '0');
         i++;
     }
  
     if (flag == '-')
         result = -result;
  
     // handle max and min
     if (result > Integer.MAX_VALUE)
         return Integer.MAX_VALUE;
  
     if (result < Integer.MIN_VALUE)
         return Integer.MIN_VALUE;
  
     return (int) result;
 }

更新:

因为遇见过了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  
     // check negative or positive
     int i = 0;
     if (str.charAt(0) == '-') {
         flag = '-';
         i++;
     } else if (str.charAt(0) == '+') {
         i++;
     }
     // use double to store result
     int result = 0;
  
     // calculate value
     while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
         if(Integer.MAX_VALUE/10 < result || (Integer.MAX_VALUE/10 == result && Integer.MAX_VALUE%10 < (str.charAt(i) - '0'))) 
             return flag == '-' ? Integer.MIN_VALUE : Integer.MAX_VALUE;
             
         result = result * 10 + (str.charAt(i) - '0');
         i++;
     }
  
     if (flag == '-')
         result = -result;
  
     return result;
 }

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

最新文章

  1. 几种排序算法的学习,利用Python和C实现
  2. 012 VS2013常用快捷键
  3. java mail使用qq邮箱发邮件的配置方法
  4. Visual Studio中删除所有空行
  5. Python之控制台输入密码的方法
  6. Linux_08------Linux的系统管理
  7. wordpress安装记录
  8. tomcat 默认项目设置
  9. webkit的基本应用
  10. Log4J使用笔记(转)
  11. (未解决)在JSTL中,session 和 sessionScope 有什么区别 ??
  12. iOS 在下面 AOP 程序
  13. Linux、GUN/Linux、GUN、GPL以及各个发行版本详细介绍
  14. ssh相关命令
  15. java api1.8中文版(由谷歌,百度,有道,必应翻译).md
  16. Android中Parcelable接口
  17. Windows内核中的内存管理
  18. TP中的图片水印
  19. 何在mysql查找效率慢的SQL语句?
  20. Luogu4770 NOI2018你的名字(后缀数组+线段树)

热门文章

  1. 测试开发之前端——No7.HTML5中的鼠标事件
  2. Iterator 接口
  3. 《剑指offer》-整数中1出现的次数
  4. 《剑指offer》-前n项和不准用通解和各种判断
  5. jq:翻页时,保存上页多选框checkbox选中状态
  6. Java编程的逻辑 (12) - 函数调用的基本原理
  7. kotlin 插件更新到 1.2.41 程序出错 Please use kotlin-stdlib-jdk7 instead
  8. Json的简单使用
  9. 【AtCoder】CODE FESTIVAL 2017 qual C
  10. BZOJ3545 [ONTAK2010]Peaks kruskal 并查集 主席树 dfs序