题目:

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

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.

链接:http://leetcode.com/problems/string-to-integer-atoi/

题解:

这道题试了好多次才ac,在Microsoft onsite的第三轮里也被问到过如何解决和测试。主要难点就是处理各种corner case。假如面试中遇到,一定要和面试官多沟通交流,确定overflow,underflow以及invalid的时候,应该返回什么值。判断时不可以使用long才hold溢出情况,一般都是比较当前数值和Integer.MAX_VALUE / 10 或者Integer.MIN_VALUE / 10。

以下是一个AC解法,主要方法是

1). 判断输入是否为空

2). 用trim()去除string前后的空格

3). 判断符号

4). 假如符号位后连续几位是有效的数字,对数字进行计算,同时判断是否overflow或者underflow。

5). 返回数字

public class Solution {public int myAtoi(String str) {if(str == null || str.length() == 0)return 0;str = str.trim();int index = 0, result = 0;boolean isNeg = false;if(str.charAt(index) == '+')index ++;else if(str.charAt(index) == '-'){isNeg = true;index ++;}while(index < str.length() && str.charAt(index) >= '0' && str.charAt(index) <= '9'){     //deal with valid input numbersif(result > Integer.MAX_VALUE / 10){return isNeg ? Integer.MIN_VALUE : Integer.MAX_VALUE;                           // case "      -11919730356x", the result should be 0?
            } else if( result == Integer.MAX_VALUE / 10){                       if((!isNeg) && ((str.charAt(index) - '0') > Integer.MAX_VALUE % 10) ) return Integer.MAX_VALUE;else if (isNeg && ((str.charAt(index) - '0') > (Integer.MAX_VALUE % 10 + 1)))return Integer.MIN_VALUE;}result = result * 10 + (str.charAt(index) - '0');  index ++; }return isNeg ? -result : result;}
}

Python:

Java式Python... sigh,不知道什么时候才可以写得优雅简练。   检查Python里字符是否为数字一般有两种方法,一种是c.isdigit(), 另外可以尝试用try catch

try:int(c)
except ValueError:pass

Time Complexity - O(n),  Space Complexity - O(1)

class Solution(object):max_value = 2147483647min_value = -2147483648def myAtoi(self, str):""":type str: str:rtype: int"""if str == None or len(str) == 0:return 0index = 0while str[index] == ' ':index += 1sign = 1if str[index] in ('+', '-'):if str[index] == '-':sign = -1index += 1res = 0    while index < len(str):c = str[index]num = 0if c.isdigit():num = int(c)if res > self.max_value / 10:return self.max_value if sign == 1 else self.min_valueelif res == self.max_value / 10:if sign == -1 and num > 8:return self.min_valueelif sign == 1 and num > 7:return self.max_valueres = res * 10 + numelse:return res * signindex += 1return res * sign

测试:

1. "+-2"

2. "    123  456"

3. "      -11919730356x"

4. "2147483647"

5. "-2147483648"

6. "2147483648"

7. "-2147483649"

二刷:

Time Complexity - O(n), Space Complexity - O(1)

Java: 二刷思路就比较清晰。依然是有下面几个步骤:

  1. 判断str是否为空或者长度是否为0
  2. 处理前部的space,也可以用str = str.trim();
  3. 尝试求出符号sign
  4. 定义结果int res = 0 ,  处理数字
    1. 假如char c = str.charAt(index)是数字,则定义int num = c - '0', 接下来判断是否越界

      1. 当前 res > Integer.MAX_VALUE / 10,越界,根据sign 返回 Integer.MAX_VALUE或者 Integer.MIN_VALUE
      2. res == Integer.MAX_VALUE / 10时, 根据最后sign和最后一位数字来决定是否越界,返回Integer.MAX_VALUE或者 Integer.MIN_VALUE
      3. 不越界情况下,res = res * 10 + num
    2. 否则返回当前 res * sign
  5. 返回结果 res * sign

这里比较tricky的点是,从Integer.MAX_VALUE和Integer.MIN_VALUE越界时要分别返回Integer.MAX_VALUE或者Integer.MIN_VALUE。假如当前字符不为数字,则返回之前已经计算过的,到这一位为止的res * sign。

public class Solution {public int myAtoi(String str) {if (str == null || str.length() == 0) {return 0;}int index = 0;while (str.charAt(index) == ' ') {index++;}int sign = 1;if (str.charAt(index) == '+' || str.charAt(index) == '-') {if (str.charAt(index) == '-') {sign = -1;}index++;}int res = 0;while (index < str.length()) {char c = str.charAt(index);if (c >= '0' && c <= '9') {int num = c - '0';if (res > Integer.MAX_VALUE / 10) {return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;} else if (res == Integer.MAX_VALUE / 10) {if (sign == -1 && num > 8) {return Integer.MIN_VALUE;} else if (sign == 1 && num > 7) {return Integer.MAX_VALUE;}}  res = res * 10 + num;} else {return res * sign;}index++;}return res * sign;}
}

三刷:

写多了也就顺了。还是要多写

Java:

Time Complexity - O(n),  Space Complexity - O(1)

public class Solution {public int myAtoi(String str) {if (str == null || str.length() == 0) return 0;str = str.trim();int index = 0;boolean isNeg = false;if (str.charAt(index) == '-') {isNeg = true;index++;} else if (str.charAt(index) == '+') {index++;}int res = 0;while (index < str.length()) {char c = str.charAt(index);if (c > '9' || c < '0') return isNeg ? -res : res;if (res > Integer.MAX_VALUE / 10) {return isNeg ? Integer.MIN_VALUE : Integer.MAX_VALUE;} else if (res == Integer.MAX_VALUE / 10) {if (isNeg && (c - '0') > 8) return Integer.MIN_VALUE;else if (!isNeg && (c - '0') > 7) return Integer.MAX_VALUE;}res = res * 10 + c - '0';index++;}return isNeg ? -res : res;}
}

Python:

Reference:

转载于:https://www.cnblogs.com/yrbbest/p/4430375.html

8. String to Integer (atoi)相关推荐

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

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

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

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

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

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

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

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

  5. String to Integer (atoi) leetcode java

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

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

  7. LeetCodeOJ. String to Integer (atoi)

    试题请參见: https://oj.leetcode.com/problems/string-to-integer-atoi/ 题目概述 Implement atoi to convert a str ...

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

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

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

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

最新文章

  1. NB-IOT UE的小区接入过程
  2. 区分BundleVersion和BundleShortVersionString
  3. 编程界称霸全球的10大算法,你到底了解几个呢?
  4. sgu 175 Encoding
  5. 浏览器缓存原理以及本地存储
  6. Oracle 数字与空值的排序问题
  7. PAYPAL使用虚拟信用卡验证的技巧
  8. java2wsdl_Java2WSDL之java实现
  9. 【静态网页制作大作业——个人博客搭建(HTML+CSS+Javascript)】
  10. win10无法安装迅雷精简版解决办法
  11. 最简单的基于FFMPEG的封装格式转换器(致敬雷霄骅)
  12. 小程序运营主要做什么?如何推广比较好?
  13. Fantom (FTM) 价格将在未来几天飙升 20%
  14. 谷歌浏览器怎么关闭硬件加速?
  15. 个人申请微信公众号步骤(含截图)
  16. panic: time: missing Location in call to Time.In
  17. mysql下镜像安装教程_mysql的下载和安装详细教程(windows)
  18. sublime 的一个神秘快捷键
  19. promise是什么及其用法
  20. Android解决小米手机相机和相册的问题(适配小米手机相机和相册)

热门文章

  1. mysql相关操作(一)
  2. Sql Server中两个表之间数据备份和导入
  3. codesmith用access的mdb文件作数据源的模板引用
  4. DXPerience6.x 使用体会(二)
  5. MySQL学习(十五)
  6. 导航栏下拉菜单效果代码
  7. android--------内存泄露分析工具—Android Monitor
  8. 《Visual C# 2010入门经典》一导读
  9. jvm系列(十):如何优化Java GC「译」
  10. 基于SharePoint 2013的论坛解决方案[开源]