LeetCode: String to Integer (atoi) 解题报告
String to Integer (atoi)
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.
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.
Solution
1. 用String s = str.trim();裁掉前面后面的空格。
2. 记录起始的+,-符号。
3. 用Long来转数字,这样的话就算越界也没什么了。
public class Solution {
public int atoi(String str) {
if (str == null) {
return 0;
}
// remove the spaces in the begining and the end.
String s = str.trim();
boolean minus = false;
long num = 0;
for (int i = 0; i < s.length(); i++) {
/*
takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
*/
if (i == 0 && s.charAt(i) == '+') {
continue;
} else if (i == 0 && s.charAt(i) == '-'){
// get the
minus = true;
continue;
}
int c = s.charAt(i) - '0';
if (c > 9 || c < 0) {
// invalid character.
break;
}
num = num * 10 + c;
}
// If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is // returned.
if (minus) {
num = -num;
num = Math.max(num, Integer.MIN_VALUE);
} else {
num = Math.min(num, Integer.MAX_VALUE);
}
return (int)num;
}
}
2015.1.3 redo,
leetcode升级了test case,加入了更大的比long还大的数。这样我们必须在循环里就判断是不是越界就退出了,否则long也会爆掉的。
public class Solution {
public int atoi(String str) {
long ret = 0;
// ___+1234__
// Delete the leading and tailing spaces.
String sNew = str.trim();
if (sNew.length() == 0) {
return 0;
}
boolean positive = true;
for (int i = 0; i < sNew.length(); i++) {
char c = sNew.charAt(i);
if (i == 0 && c == '+') {
continue;
} else if (i == 0 && c == '-') {
positive = false;
continue;
}
if (!(c <= '9' && c >= '0')) {
break;
}
int dig = positive ? c - '0': '0' - c;
ret = ret * 10 + dig;
// bug 2: should consider the out of range.
if (ret > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (ret < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
}
return (int)ret;
}
}
GitHub
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/Atoi.java
LeetCode: String to Integer (atoi) 解题报告的更多相关文章
- 【LeetCode】String to Integer (atoi) 解题报告
这道题在LeetCode OJ上难道属于Easy.可是通过率却比較低,究其原因是须要考虑的情况比較低,非常少有人一遍过吧. [题目] Implement atoi to convert a strin ...
- 【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 "& ...
随机推荐
- placement new 笔记
之前看到 偶尔用placement new 的用法,当分配内存频繁,而且对效率要求很高的情况下,可以先申请一块大内存,然后在此内存上构建对象,关键是可以自动调用其构造函数,否则要悲剧. 但是之后要自己 ...
- 【基础】centos 6.X 下修改图形界面为命令行界面(单用户救援模式)
1. Linux开机引导的时候,按键盘上的e 就可以进入进入GRUB菜单界面. 2.在出现GRUB引导画面时(CentOS(2.6.18-274**)),按字母e键,进入GRUB编辑状态: 3.把光标 ...
- Windbg(2)
摘抄于:http://www.cnblogs.com/awpatp/category/228209.html Debug相关的一些小技巧 摘要: 1. 如何Debug一个进程的子进程? 答: 使用Wi ...
- 【Spring】SpringMVC之拦截器
Spring的HandlerMapping处理器支持拦截器应用.当需要为某些请求提供特殊功能时,例如实现对用户进行身份认证.登录检查等功能. 拦截器必须实现HandlerInterceptor接口,实 ...
- 用copy 还是 strong?
NSArray与NSMutableArray用copy修饰还是strong 这个是原文 http://blog.csdn.net/winzlee/article/details/51752354 一 ...
- numpy中的np.random.mtrand.RandomState
1 RandomState 的应用场景概述 在训练神经网络时,苦于没有数据,此时numpy为我们提供了 “生产” 数据集的一种方式. 例如在搭建神经网络(一)中的 4.3 准备数据集 章节中就是采用n ...
- 安卓获取ListView、GridView等滚动的距离(高度)
public int getScrollY() { View c = mListView.getChildAt(0); if (c == null) { return 0; } int firstVi ...
- 数字的可视化:python画图之散点图sactter函数详解
最近开始学习python编程,遇到scatter函数,感觉里面的参数不知道什么意思于是查资料,最后总结如下: 1.scatter函数原型 2.其中散点的形状参数marker如下: 3.其中颜色参数c如 ...
- Linux内核同步:RCU
linux内核 RCU机制详解 简介 RCU(Read-Copy Update)是数据同步的一种方式,在当前的Linux内核中发挥着重要的作用.RCU主要针对的数据对象是链表,目的是提高遍历读取数据的 ...
- exp、Exploit、Exploit Pack、exp-gui、Payload、MetaSploit都是啥?
对于走在安全路上的小菜来说,这几个exp.Exploit.Exploit Pack.exp-gui.Payload.MetaSploit名词着实把人转的不轻,以下给大家解释下: Exp,就是Explo ...