题目

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/

String to Integer (atoi) leetcode java的更多相关文章

  1. String to Integer (atoi) leetcode

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

  2. String to Integer (atoi) ---- LeetCode 008

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

  3. 8. String to Integer (atoi) ---Leetcode

    Implement atoi to convert a string to an integer. 题目分析: 题目本身很简单就是将一个字符串转化成一个整数,但是由于字符串的千差万别,导致在实现的时候 ...

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

    8. 字符串转换整数 (atoi) 8. String to Integer (atoi) 题目描述 LeetCode LeetCode8. String to Integer (atoi)中等 Ja ...

  5. LeetCode【8】. String to Integer (atoi) --java实现

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

  6. leetcode第八题 String to Integer (atoi) (java)

    String to Integer (atoi) time=272ms   accepted 需考虑各种可能出现的情况 public class Solution { public int atoi( ...

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

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

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

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

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

随机推荐

  1. python 全栈开发,Day43(引子,协程介绍,Greenlet模块,Gevent模块,Gevent之同步与异步)

    昨日内容回顾 I/O模型,面试会问到I/O操作,不占用CPU.它内部有一个专门的处理I/O模块.print和写log 属于I/O操作,它不占用CPU 线程GIL保证一个进程中的多个线程在同一时刻只有一 ...

  2. 步步为营-17-FileStream-文件加密/解密

    以前使用的File是操作小的文本文件,用的并不常见,FileStream(操作字节),可以操作所有格式的文件,用途较广泛 下面做一个通过文件流给文件加密解密的小软件. using System; us ...

  3. C# event关键字

    直接使用委托的写法,如下: using System; namespace ConsoleAppTest { class Program { class Test { static void Main ...

  4. User Agent 设置

    感谢版主回复,版主贴的方法网上到处都是,我试了很多次都是不行的,有用的方法都几乎这个到处转贴的信息淹没了. 今天我总算在一个博客找了到可行的方法,转过来和大家分享 Windows Registry E ...

  5. BZOJ4994 [Usaco2017 Feb]Why Did the Cow Cross the Road III 树状数组

    欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - BZOJ4994 题意概括 给定长度为2N的序列,1~N各处现过2次,i第一次出现位置记为ai,第二次记为bi ...

  6. 043 HIVE中的HQL操作

    1.字段查询 select empno,ename from emp; 2.过滤where,limit,distinct select * from emp where sal >2500; s ...

  7. [OpenCV-Python] OpenCV 中的 Gui特性 部分 II

    部分 IIOpenCV 中的 Gui 特性 OpenCV-Python 中文教程(搬运)目录 4 图片 目标 • 在这里你将学会怎样读入一幅图像,怎样显示一幅图像,以及如何保存一幅图像 • 你将要学习 ...

  8. POJ 2437 Muddy roads【贪心】(区间覆盖)

    题目链接:https://vjudge.net/contest/194475#problem/C 题目大意: 有n滩泥 木板长度为L 求至少需要多少木板才能覆盖这些泥 解题思路: 把泥块的起点升序排序 ...

  9. css实现幻灯片播放效果

    用css实现幻灯片播放是最基础的,闲下来没事就试着写了一下,如果有不够完善或者方法不好的地方还请指点.下面我就用两种方法实现css花灯片效果. 方法1:定位.通过position属性改变left值 h ...

  10. idea springboot热部署无效问题

    Intellij IDEA 使用Spring-boot-devTools无效解决办法 springboot项目中遇到的bug <dependencies> <!--spring bo ...