[leetcode]8. String to Integer (atoi)字符串转整数
Implement atoi
which converts a string to an integer.
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.
Note:
- Only the space character
' '
is considered as whitespace character. - Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 2^31 − 1]. If the numerical value is out of the range of representable values, INT_MAX (2^31 − 1) or INT_MIN (−231) is returned.
Example 1:
Input: "42"
Output: 42
Example 2:
Input: " -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore INT_MIN (−231) is returned.
题目
字符串转整数
思路
小心各种corner case
代码
class Solution {
public int myAtoi(String str) {
str = str.trim(); // handle str = " "的情况, 此时str.length() = 4, 不会走第一个if语句,从而会造成后续指针的outofbound
if (str == null || str.length() == 0)
return 0; char c = str.charAt(0);
int sign = 1, start = 0, len = str.length();
long sum = 0;
// take care of sign
if (c == '+') {
sign = 1;
start++;
} else if (c == '-') {
sign = -1;
start++;
} for (int i = start; i < len; i++) {
// take care of non numerical digit, like 'w'
if (!Character.isDigit(str.charAt(i))){
return (int) sum * sign;
}
// convert each char to each digit
sum = sum * 10 + str.charAt(i) - '0';
// Input: "-91283472332" Output:-2147483648
if (sign == 1 && sum > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
//思考为何不能写成 if(sign == -1 && sum > Integer.MAX_VALUE)
if (sign == -1 && (-1) * sum < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
}
return (int) sum * sign;
}
}
注意: line11-14 显得很多余,因为通常正整数前不会专门写 ‘+’ 号。 但确实有这样的test case(如下图), 所以写上这个条件,会更加严谨。
[leetcode]8. String to Integer (atoi)字符串转整数的更多相关文章
- [LeetCode] 8. String to Integer (atoi) 字符串转为整数
Implement atoi which converts a string to an integer. The function first discards as many whitespace ...
- 【LeetCode】String to Integer (atoi)(字符串转换整数 (atoi))
这道题是LeetCode里的第8道题. 题目要求: 请你来实现一个 atoi 函数,使其能将字符串转换成整数. 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止. 当我们 ...
- [LeetCode] String to Integer (atoi) 字符串转为整数
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- 【LeetCode】8. String to Integer (atoi) 字符串转换整数
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:字符串转整数,atoi,题解,Leetcode, 力扣,P ...
- Leetcode8.String to Integer (atoi)字符串转整数(atoi)
实现 atoi,将字符串转为整数. 该函数首先根据需要丢弃任意多的空格字符,直到找到第一个非空格字符为止.如果第一个非空字符是正号或负号,选取该符号,并将其与后面尽可能多的连续的数字组合起来,这部分字 ...
- 【LeetCode】8. String to Integer (atoi) 字符串转整数
题目: Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input ca ...
- Leetcode 8 String to Integer (atoi) 字符串处理
题意:将字符串转化成数字. 前置有空格,同时有正负号,数字有可能会溢出,这里用long long解决(leetcode用的是g++编译器),这题还是很有难度的. class Solution { pu ...
- LeetCode OJ String to Integer (atoi) 字符串转数字
#include <iostream> #include <assert.h> using namespace std; int ato(const char *str) { ...
- 008 String to Integer (atoi) 字符串转换为整数
详见:https://leetcode.com/problems/string-to-integer-atoi/description/ 实现语言:Java class Solution { publ ...
随机推荐
- 转载:python list和set的性能比较+两者转换
两者性能比较(转自http://www.linuxidc.com/Linux/2012-07/66404.htm) 本来是知道在Python中使用Set是比较高效,但是没想到竟然有这么大的差距: ~$ ...
- Hystrix 学习使用
说明: 每次调用创建一个新的HystrixCommand,把依赖调用封装在run()方法中 执行execute()/queue做同步或异步调用 请求接收后,会先看是否存在缓存数据,如果存在,则不会继续 ...
- Guava 3: 集合Collections
一.引子 Guava 对JDK集合的拓展,是最成熟且最受欢迎的部分.本文属于Guava的核心,需要仔细看. 二.Guava 集合 2.1 Immutable Collections不可变集合 1.作用 ...
- 剑指offer 3. 链表 从尾到头打印链表
题目描述 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList. 解题思路:利用栈先进后出的原理,依次把ArrayList的值入栈,再出栈即可逆序 import java.util.Arra ...
- property用法
用法一 class Test(object): def __init__(self): self.__Num = 100 def setNum(self,Num): print("---se ...
- spring boot项目使用外部tomcat启动失败总结
1. springboot的tomcat使用外部提供的. dependency> <groupId>org.springframework.boot</groupId> ...
- 记录 Ext 日历月份选择控件bug解决过程结果
目录 背景 代码 背景 项目使用 Ext.NET 2.2.0.40838 , 对应 Ext JS4.2 版本. 结果 2017/3/31 号的时候偶然间点日历选择控件选择2月,10月等月份突然就跳到3 ...
- WM消息对应的Message消息中的Lparam和WParam
具体的消息表示: 1. WM_PAINT消息,LOWORD(lParam)是客户区的宽,HIWORD(lParam)是客户区的高 2. 滚动条WM_VSCROLL或WM_HSCROLL消息,LOWOR ...
- 【Linux】【Jenkins】配置过程中,立即构建时,maven找不到的问题解决方案
在Linux环境下配置Jenkins执行时,发现不能执行Maven,这个比较搞了. A Maven installation needs to be available for this projec ...
- Merge Into 语句代替Insert/Update在Oracle中的应用实战
动机: 想在Oracle中用一条SQL语句直接进行Insert/Update的操作. 说明: 在进行SQL语句编写时,我们经常会遇到大量的同时进行Insert/Update的语句 ,也就是说当存在记录 ...