【LeetCode】String to Integer (atoi) 解题报告
这道题在LeetCode OJ上难道属于Easy。可是通过率却比較低,究其原因是须要考虑的情况比較低,非常少有人一遍过吧。
【题目】
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.
spoilers alert... click to show 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 跟C++实现的不一样吧。比方我以为不符合要求的返回-1,而这道题要求返回0。
所以,有必要解释一下题目的要求:
1. 首先须要丢弃字符串前面的空格;
2. 然后可能有正负号(注意仅仅取一个,假设有多个正负号。那么说这个字符串是无法转换的,返回0。比方測试用例里就有个“+-2”);
3. 字符串能够包括0~9以外的字符,假设遇到非数字字符,那么仅仅取该字符之前的部分,如“-00123a66”返回为“-123”;
4. 假设超出int的范围,返回边界值(2147483647或-2147483648)。
综上,要求还是有点怪的,不看要求是非常难写对的,看了也不一定理解的对。
【Java代码】
public class Solution {
public int atoi(String str) {
// 1. null or empty string
if (str == null || str.length() == 0) return 0;
// 2. whitespaces
str = str.trim();
// 3. +/- sign
boolean positive = true;
int i = 0;
if (str.charAt(0) == '+') {
i++;
} else if (str.charAt(0) == '-') {
positive = false;
i++;
}
// 4. calculate real value
double tmp = 0;
for ( ; i < str.length(); i++) {
int digit = str.charAt(i) - '0';
if (digit < 0 || digit > 9) break;
// 5. handle min & max
if (positive) {
tmp = 10*tmp + digit;
if (tmp > Integer.MAX_VALUE) return Integer.MAX_VALUE;
} else {
tmp = 10*tmp - digit;
if (tmp < Integer.MIN_VALUE) return Integer.MIN_VALUE;
}
}
int ret = (int)tmp;
return ret;
}
}
參考 http://www.programcreek.com/2012/12/leetcode-string-to-integer-atoi/ ,代码例如以下:
public int atoi(String str) {
if (str == null || str.length() < 1)
return 0;
// trim white spaces
str = str.trim();
char flag = '+';
// check negative or positive
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
// use double to store result
double result = 0;
// calculate value
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = result * 10 + (str.charAt(i) - '0');
i++;
}
if (flag == '-')
result = -result;
// handle max and min
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
return (int) result;
}
代码看起来更简洁,可是第一种写法能够及时跳出循环。不用计算完了再推断是否越界。
【LeetCode】String to Integer (atoi) 解题报告的更多相关文章
- LeetCode: String to Integer (atoi) 解题报告
String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...
- 【LeetCode】397. Integer Replacement 解题报告(Python)
[LeetCode]397. Integer Replacement 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/inte ...
- [LeetCode] String to Integer (atoi) 字符串转为整数
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- [Leetcode] String to integer atoi 字符串转换成整数
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- [LeetCode] String to Integer (atoi) 字符串
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- 【LeetCode】343. Integer Break 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 数学解法 动态规划 日期 题目地址:https:// ...
- [Leetcode]String to Integer (atoi) 简易实现方法
刚看到题就想用数组做,发现大多数解也是用数组做的,突然看到一个清新脱俗的解法: int atoi(const char *str) { ; int n; string s(str); istrings ...
- [LeetCode]String to Integer (atoi)
题意:字符串转正数 原题来自:https://leetcode.com/problems/string-to-integer-atoi/ 分析: <程序员面试宝典>上出现的面试题,主要是考 ...
- leetcode String to Integer (atoi) python
class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int "& ...
随机推荐
- 识骨寻踪第一季/全集Bones迅雷下载
第一季 Bones Season 1 (2005)看点:这是一部专门从“骨头”上寻找破案线索的刑侦剧.女博士布莱南绰号“骨头”(艾米丽·丹斯切尔 Emily Deschanel 饰),是个学识渊博.专 ...
- 快速找到自己想要用到的cocos2d-x的缓冲动画
游戏中在做很多动画时,需要用到缓冲来增强表现.比如宝箱"鼓"几下,然后"蹦"的一下打开.很多时候要调效果时,需要轮着试,如果有一张图和实际示例效果,那就省很多事 ...
- 推荐一款移动端的web UI控件 -- mobiscroll
用mobiscroll 可实现ios系统自带的选择器控件效果,支持几乎所有的移动平台(iOS, Android, BlackBerry, Windows Phone 8, Amazon Kindle) ...
- Svg.Js 简介(转)
什么是SVG? SVG 指可伸缩矢量图形 (Scalable Vector Graphics) SVG 用来定义用于网络的基于矢量的图形 SVG 使用 XML 格式定义图形 SVG 图像在放大或改变尺 ...
- Ubuntu apt-get 彻底卸载软件包
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/get_set/article/details/51276609 如果你关注搜索到这篇文章,那么我可以 ...
- RAISR: rapid and accurate image super resolution
准确地说,RAISR并不是用来压缩图像的,而是用来upsample图像的. 众所周知,图片缩小到半分辨率后,在拉回原大小,会出现强烈的锯齿.从80年代开始就有很多super sampling的方法 ...
- 利用Microsoft.Exchange.WebServices处理Office365邮件的几个属性
使用Microsoft.Exchange.WebServices可以很方便操作Office365邮件.这里列出几个重要的属性. 通常,代码里会先定义一个WebServices对象 ExchangeSe ...
- Dalvik虚拟机的内存管理
Dalvik虚拟机的内存分为三种类型: Java Object Heap, Bitmap Memory, Native Heap. 下面,就这三种类型进行详细讲解: 一. J ...
- go语言之进阶篇文件常用操作接口介绍和使用
一.文件常用操作接口介绍 1.创建文件 法1: 推荐用法 func Create(name string) (file *File, err Error) 根据提供的文件名创建新的文件,返回一个文件对 ...
- easyui combobox默认选中项
今天写前端代码发现combobox还挺难搞, $("#select_Dic").combobox({ url: "http: ...