题目

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. Python3中高阶函数lambda,filter,map,reduce,zip的详细用法

    在Python里有五大高阶函数,他们分别是lambda()匿名函数,filter()筛选函数,map()函数,reduce()函数,zip()函数.下面就让我们来详细的了解一下这五种函数的具体用法吧. ...

  2. LIFO栈 ADT接口 实现十进制转其他进制

    LIFO 接口 Stack.h //LIFO 链栈初始化 void InitStack(Stack top){ //LIFO 链栈判断栈空 boolean StackKEmpty(Stack top) ...

  3. 20155234 2016-2017-2 《Java程序设计》第3 周学习总结

    20155234 2006-2007-2 <Java程序设计>第3周学习总结 教材学习内容总结 类是对象的设计图,对象是类的实例. 参考名称与对象数据成员同名时,可以在数据成员前使用thi ...

  4. 20155323 2016-2017-2《Java程序设计》课程总结

    20155323 2016-2017-2<Java程序设计>课程总结 课程与实验链接 预备作业一:新学期,新展望 预备作业二:游戏经验 预备作业三:安装虚拟机和Linux系统的学习 201 ...

  5. [BZOJ3678]wangxz与OJ-[Splay一类的平衡树]

    Description 传送门 Solution 直接splay搞定吧..似乎非旋treap也ok? 我已经菜到模板题都写不出来了qaq Code #include<iostream> # ...

  6. Drupal8 使用模块的配置文件

    D8中移除了variable表及相关方法 (variable_get(),variable_set()等) .用config表取代了. 新的方法该如何使用? 以D8的Youtube模块为例 配置文件要 ...

  7. Linux 防火墙设置(转)

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 3 ...

  8. MySQL数据库之数据类型和完整性约束

    补充: select * from mysql.user #显示出来乱了 select * from mysql.user\G #加了\G后一行一行显示了 一.数据类型:分不同种类去存不同类型的数据 ...

  9. python全栈开发-面向对象-初识

    python_16_day 函数总结: https://www.processon.com/view/link/5b718274e4b0555b39e1055f 面向过程的程序设计的核心是过程(流水线 ...

  10. Qt-Qt5最新增加程序图标方式

    亲爱的小伙伴吗,还记得原始的Qt4是怎么给运行程序添加图标的么,是不是先准备一个ICON文件,问了在家里建立一个rc文件,在文件里面加上 IDI_ICON1               ICON    ...