蜗牛慢慢爬 LeetCode 8. String to Integer (atoi) [Difficulty: Medium]
题目
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]的更多相关文章
- 蜗牛慢慢爬 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 ...
- 蜗牛慢慢爬 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. ...
- 蜗牛慢慢爬 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 ...
- # 蜗牛慢慢爬 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 ...
- Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串)
Leetcode 8. String to Integer (atoi) atoi函数实现 (字符串) 题目描述 实现atoi函数,将一个字符串转化为数字 测试样例 Input: "42&q ...
- leetcode day6 -- String to Integer (atoi) && 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 ...
- 【leetcode】String to Integer (atoi)
String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...
- [leetcode] 8. String to Integer (atoi) (Medium)
实现字符串转整形数字 遵循几个规则: 1. 函数首先丢弃尽可能多的空格字符,直到找到第一个非空格字符. 2. 此时取初始加号或减号. 3. 后面跟着尽可能多的数字,并将它们解释为一个数值. 4. 字符 ...
- Leetcode 8. String to Integer (atoi)(模拟题,水)
8. String to Integer (atoi) Medium Implement atoi which converts a string to an integer. The functio ...
随机推荐
- 智能家居系统 Home Assistant 系列 --介绍篇
一. HomeAssistant 是什么? HomeAssistant是构建智慧空间的神器.是一个成熟完整的基于 Python 的智能家居系统,设备支持度高,支持自动化(Automation).群组化 ...
- sklearn的train_test_split,果然很好用啊!
sklearn的train_test_split train_test_split函数用于将矩阵随机划分为训练子集和测试子集,并返回划分好的训练集测试集样本和训练集测试集标签. 格式: X_tra ...
- Linux了解一下
VMware与CentOS系统安装 1, 下载CentOS系统ISO镜像: 国内镜像源 https://opsx.alibaba.com/mirror#阿里云官方镜像站 iso下载地址(此DVD映像包 ...
- JVM类加载机制概述
首先类加载在整个体系结构的哪一个环节呢?见红色圈住的部分. 类加载器分为那几个过程呢?五个过程 加载 根据类的全限定名(简单理解为类的绝对路径,见附录),找到指定的字节码文件,并在内存中生产一个jav ...
- 2017-2018-1 20155307《信息安全技术李冬冬》实验二——Windows口令破解
2017-2018-1 <信息安全技术>实验二--Windows口令破解 所需工具: 试验系统:Windows 2003 实验工具:LC5.SuperDic 口令破解主要有两种方法:字典破 ...
- 【LG3230】[HNOI2013]比赛
题面 洛谷 题解 代码 \(50pts\) #include<iostream> #include<cstdio> #include<cstdlib> #inclu ...
- LVS入门篇(二)之LVS基础
1. LVS介绍 LVS是Linux虚拟服务器(LinuxVirtualServers),使用负载均衡技术将多台服务器组成一个虚拟服务器.它为适应快速增长的网络访问需求提供了一个负载能力易于扩展,而价 ...
- python全栈开发-前方高能-内置函数2
python_day_15 一.今日主要内容 1. lambda 匿名函数 语法: lambda 参数:返回值 不能完成复杂的操作 2. sorted() 函数 排序. 1. 可迭代对象 2. key ...
- VirtualBox虚拟机上安装windows7系统
1.下载Windows7的镜像文件 http://www.xitongcheng.com/jiaocheng/win7_article_24156.html 2.在虚拟机上安装Windows7 htt ...
- Linux系统中Oracle11g数据库的安装与验证
1.查看Linux系统的位数 2.下载Oracle10g数据库软件 https://blog.csdn.net/xiezuoyong/article/details/81197688 (需要注册Ora ...