1. Implement atoi to convert a string to an integer.
  2.  
  3. 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.
  4.  
  5. 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.
  6.  
  7. spoilers alert... click to show requirements for atoi.
  8.  
  9. Requirements for atoi:
  10. 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.
  11.  
  12. 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.
  13.  
  14. 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.
  15.  
  16. 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.

抠细节的题目,特别是 Integer.MIN_VALUE 与 Integer.MAX_VALUE的绝对值并不一样大. 一般要分开处理,但我这里16-17行统一处理也是可行的,原因在于用的是>号,当res 绝对值为2147483647时,给res加正号或者加负号都是可以的,不需要特殊处理;只有当res绝对值为2147483648或更大时才需要特别处理,如果是正数则处理为Integer.MAX_VALUE,如果是负数则处理为Integer.MIN_VALUE(与直接给2147483648加上负号效果一样)。整数一般有两点,一个是正负符号问题,另一个是整数越界问题。

  1. public class Solution {
  2. public int atoi(String str) {
  3. int res = 0;
  4. if (str==null || str.length()==0) return res;
  5. str = str.trim();
  6. if (str.length() == 0) return res;
  7. boolean isNeg = false;
  8. for (int i=0; i<str.length(); i++) {
  9. if (i == 0 && str.charAt(i) == '+') continue;
  10. else if (i == 0 && str.charAt(i) == '-') {
  11. isNeg = true;
  12. continue;
  13. }
  14. else if (str.charAt(i)>='0' && str.charAt(i)<='9') {
  15. int digit = (int)(str.charAt(i) - '0');
  16. if (res > (Integer.MAX_VALUE - digit) / 10) {
  17. return isNeg? Integer.MIN_VALUE : Integer.MAX_VALUE;
  18. }
  19. res = res * 10 + digit;
  20. }
  21. else break;
  22. }
  23. return isNeg? -res : res;
  24. }
  25. }

转载一个不错的解法(跟我差不多):

  1. public int atoi(String str) {
  2. if(str==null)
  3. {
  4. return 0;
  5. }
  6. str = str.trim();
  7. if(str.length()==0)
  8. return 0;
  9. boolean isNeg = false;
  10. int i = 0;
  11. if(str.charAt(0)=='-' || str.charAt(0)=='+')
  12. {
  13. i++;
  14. if(str.charAt(0)=='-')
  15. isNeg = true;
  16. }
  17. int res = 0;
  18. while(i<str.length())
  19. {
  20. if(str.charAt(i)<'0'||str.charAt(i)>'9')
  21. break;
  22. int digit = (int)(str.charAt(i)-'0');
  23. if(isNeg && res>-((Integer.MIN_VALUE+digit)/10))
  24. return Integer.MIN_VALUE;
  25. else if(!isNeg && res>(Integer.MAX_VALUE-digit)/10)
  26. return Integer.MAX_VALUE;
  27. res = res*10+digit;
  28. i++;
  29. }
  30. return isNeg?-res:res;
  31. }

Leetcode: String to Integer的更多相关文章

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

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

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

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

  3. [LeetCode]String to Integer (atoi)

    题意:字符串转正数 原题来自:https://leetcode.com/problems/string-to-integer-atoi/ 分析: <程序员面试宝典>上出现的面试题,主要是考 ...

  4. [Leetcode] String to integer atoi 字符串转换成整数

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

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

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

  6. [Leetcode]String to Integer (atoi) 简易实现方法

    刚看到题就想用数组做,发现大多数解也是用数组做的,突然看到一个清新脱俗的解法: int atoi(const char *str) { ; int n; string s(str); istrings ...

  7. leetcode String to Integer (atoi) python

    class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int "& ...

  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. epoll 简单介绍及例子

    第一部分:Epoll简介 . 当select()返回时,timeout参数的状态在不同的系统中是未定义的,因此每次调用select()之前必须重新初始化timeout和文件描述符set.实际上,秒,然 ...

  2. 创建QT CREATOR对话框报错 linux QT Creator :-1: error: cannot find -lGL

    装完QT5.4 及 QT Creator3.3 后 创建第一个QT Widgets Application(相当于窗体) 应用程序 报如上错误. 执行 sudo apt-get install lib ...

  3. docker jenkins

    https://segmentfault.com/a/1190000003732967

  4. Android源码剖析之Framwork层消息传递(Wms到View)

    本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! 前面讲过Wms.Ams与Activity的一系列交互,包括创建过程.消息传递.窗口展示等,紧接上篇介 ...

  5. QWidget 键盘事件 焦点(QApplication源码)

    在Qt中,键盘事件和QWidget的focus密不可分:一般来说,一个拥有焦点(focus)的QWidget或者grabKeyboard()的QWidget才可以接受键盘事件. 键盘事件派发给谁? 如 ...

  6. imx6 kernel clock

    前段时间查看了uboot的时钟,kernel的也稍微了解了下,记录于此,以后再来补充完善. board-mx6q_sabresd.c MACHINE_START(MX6Q_SABRESD, " ...

  7. json和string 之间的相互转换

    json和string 之间的相互转换 <script type="text/javascript"> //先认识一下js中json function showInfo ...

  8. offset/client/scroll一些总结

    offset/client/scroll一些总结 1.offset 首先offset共有五个值 1.offsetParent 2.offsetTop 3.offsetLeft 4.offsetWidt ...

  9. https://www.zhihu.com/question/52020960#answer-47024535

    https://www.zhihu.com/question/52020960#answer-47024535

  10. Objective-C类成员变量深度剖析

    目录 Non Fragile ivars 为什么Non Fragile ivars很关键 如何寻址类成员变量 真正的“如何寻址类成员变量” Non Fragile ivars布局调整 为什么Objec ...