题目

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.

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.

翻译

实现atoi将字符串转换为整数。

提示:仔细考虑所有可能的输入案例。如果你想要一个挑战,请不要在下面看到,问自己什么是可能的输入案例。

注意:这个问题的目的是模糊地指定(即没有给定的输入规范)。您有责任收集所有的输入要求。

atoi的要求:

该函数首先丢弃尽可能多的空格字符,直到找到第一个非空格字符。然后,从该字符开始,选择一个可选的初始加号或减号,后跟尽可能多的数字,并将其解释为数值。

该字符串可以包含形成整数之后的其他字符,这些字符将被忽略,并且不影响此函数的行为。

如果str中的第一个非空白字符序列不是有效的整数,或者由于str为空或仅包含空格字符,否则不存在此类序列,则不进行转换。

如果不能执行有效的转换,则返回零值。如果正确的值超出可表示值的范围,则返回INT_MAX(2147483647)或INT_MIN(-2147483648)。

Hints

Related Topics: Math, String

代码

Java

class Solution {
public int myAtoi(String str) {
int sign = 1;
int base = 0;
int i = 0;
int INT_MAX = 2147483647;
int INT_MIN = -2147483648;
if(str.length()==0) return 0;
while(str.charAt(i)==' ') i++;
if(str.charAt(i)=='+'||str.charAt(i)=='-'){
sign = str.charAt(i++)=='+'?1:-1;
}
while(i<str.length()&&str.charAt(i)<='9'&&str.charAt(i)>='0'){
if(base > INT_MAX/10||(base==INT_MAX/10 && (str.charAt(i)-'0')>7)){
if(sign==1) return INT_MAX;
else return INT_MIN;
}
base = 10*base + (str.charAt(i++)-'0');
}
return base*sign;
}
}

Python

class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
i = base = 0
sign = 1
INT_MAX = 2147483647
INT_MIN = -2147483648
if len(str)==0:
return 0
while str[i]==' ':
i += 1
if str[i]=='-' or str[i]=='+':
sign = 1 if str[i]=='+' else -1
i += 1
while i<len(str) and str[i]<='9' and str[i]>='0':
if base > INT_MAX/10 or (base==INT_MAX/10 and int(str[i])>7):
if sign==1:return INT_MAX
else: return INT_MIN
base = 10*base + int(str[i])
i += 1
return base*sign class Solution:
def myAtoi(self, str):
str = str.strip()
if len(str) == 0:
return 0
tmp = "0"
result = 0
i = 0
if str[0] in "+-":
tmp = str[0]
i = 1
MAX_INT = 2147483647
MIN_INT = -2147483648
for i in xrange(i, len(str)):
if str[i].isdigit():
tmp += str[i]
else:
break
if len(tmp) > 1:
result = int(tmp)
if result > MAX_INT > 0:
return MAX_INT
elif result < MIN_INT < 0:
return MIN_INT
else:
return result

蜗牛慢慢爬 LeetCode 8. String to Integer (atoi) [Difficulty: Medium]的更多相关文章

  1. 蜗牛慢慢爬 LeetCode 11. Container With Most Water [Difficulty: Medium]

    题目 Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai ...

  2. 蜗牛慢慢爬 LeetCode 25. Reverse Nodes in k-Group [Difficulty: Hard]

    题目 Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. ...

  3. 蜗牛慢慢爬 LeetCode 23. Merge k Sorted Lists [Difficulty: Hard]

    题目 Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity ...

  4. # 蜗牛慢慢爬 LeetCode 21. Merge Two Sorted Lists [Difficulty: Easy]

    题目 Merge two sorted linked lists and return it as a new list. The new list should be made by splicin ...

  5. Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串)

    Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串) 题目描述 实现atoi函数,将一个字符串转化为数字 测试样例 Input: "42&q ...

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

  7. 【leetcode】String to Integer (atoi)

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

  8. [leetcode] 8. String to Integer (atoi) (Medium)

    实现字符串转整形数字 遵循几个规则: 1. 函数首先丢弃尽可能多的空格字符,直到找到第一个非空格字符. 2. 此时取初始加号或减号. 3. 后面跟着尽可能多的数字,并将它们解释为一个数值. 4. 字符 ...

  9. Leetcode 8. String to Integer (atoi)(模拟题,水)

    8. String to Integer (atoi) Medium Implement atoi which converts a string to an integer. The functio ...

随机推荐

  1. 浅谈Vue响应式(数组变异方法)

    很多初使用Vue的同学会发现,在改变数组的值的时候,值确实是改变了,但是视图却无动于衷,果然是因为数组太高冷了吗? 查看官方文档才发现,不是女神太高冷,而是你没用对方法. 看来想让女神自己动,关键得用 ...

  2. PTA基础编程题目集6-6求单链表结点的阶乘和(函数题)

    本题要求实现一个函数,求单链表L结点的阶乘和.这里默认所有结点的值非负,且题目保证结果在int范围内. 函数接口定义: int FactorialSum( List L ); 其中单链表List的定义 ...

  3. 嵌入式Linux 网络编程

    涉及到的数据结构: 下面首先介绍两个重要的数据类型:sockaddr和sockaddr_in,这两个结构类型都是用来保存socket地址信息的 定义如下所示: struct sockaddr { un ...

  4. NodeJS设置Header解决跨域问题

    转载: NodeJS设置Header解决跨域问题 app.all('*', function (req, res, next) { res.header('Access-Control-Allow-O ...

  5. Linux入门进阶第五天——用户管理(帐号管理 )下

    一.身份切换 为了避免 rm -rf /* 的悲剧发生,平时使用时,尽量使用一般帐号!需要环境设置等必要时才使用root 1.su命令 一般地,推荐使用su - / su - username的形式来 ...

  6. xgboost算法教程(两种使用方法)

    标签: xgboost 作者:炼己者 ------ 欢迎大家访问我的简书以及我的博客 本博客所有内容以学习.研究和分享为主,如需转载,请联系本人,标明作者和出处,并且是非商业用途,谢谢! ------ ...

  7. Maven学习(一)-----Maven安装配置总结

    想要安装 Apache Maven 在Windows 系统上, 需要下载 Maven 的 zip 文件,并将其解压到你想安装的目录,并配置 Windows 环境变量. 所需工具 : JDK 1.8 M ...

  8. 关于Python的装饰器(1)

    Python的装饰器的概念,一直有点微妙.之前在StackOverflow上看过一篇感觉说明的很清楚的介绍: *A decorator must accept a function as an arg ...

  9. 天下武功,无快不破,Python开发必备的6个库

    01 Python 必备之 PyPy PyPy 主要用于何处? 如果你需要更快的 Python 应用程序,最简单的实现的方法就是通过 PyPy ,Python 运行时与实时(JIT)编译器.与使用普通 ...

  10. MySql面试题(持续更新)

    1. 左连接,右连接,内连接的概念. 左连接:以左表为主,保留左表的所有数据,并且依次拿每行数据去匹配右表所有行,如果没匹配的,右边表的数据为null. 右连接:以右表为主,保留右表的所有数据,并且依 ...