[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 Django orm操作数据库笔记之QuerySet API
什么时候Django会将QuerySet转换为SQL去执行: 根据Django的数据库机制,对于QuerySet来说,当QuerySet被第一次构建,然后又调用他的filter方法,接着在对其进行切片 ...
- Matlab关于视觉问题中的一些自有API
[randsample/randperm] y = randsample(n,k);从1:n中随机抽取k个数. y= randperm(n)或者y= randperm(n,k) [rectint] ...
- python3 访问百度返回压缩格式
import urllib, urllib.request, urllib.parse import random import zlib import re import os, time Save ...
- EF 指定字段修改
public virtual void Modify(T model, params string[] ProNames) { DbEntityEntry entry = db.Entry<T& ...
- springmvc log4j配置
1. web.xml <!-- 加载Log4J 配置文件 --> <context-param> <param-name>log4jConfigLocation&l ...
- Azure SQL 数据库仓库Data Warehouse (4) 2018 TechSummit 动手实验营
<Windows Azure Platform 系列文章目录> 上传一下之前在2018 TechSummit的动手实验营:Azure数据仓库PaaS项目架构规划与实战入门 包含PPT和Wo ...
- npm i 出错
npm i npm ERR! code ECONNRESET npm ERR! errno ECONNRESET npm ERR! network request to https://registr ...
- [UE4]Safe Zone:安全区域
一.在做移动开发的时候,为了避免被手机上的硬件元素挡住界面,就可以使用Safe Zone控件,如下图所示的棕色区域就是Apple IphoneX的课被挡住界面的区域:上面的是Iphone的喇叭位置,下 ...
- python http请求及多线程应用
目录 概述 tomorrow包准备 运行环境遇到的问题 其他尝试未果 概述 今天, 使用python3 模拟下发包, http get 请求, 然后 采用tomorrow 多线程. 代码如下: # c ...
- VS调试提示“无法启动程序,“...exe”。系统找不到指定文件
当VS调试提示上图所示的警告时,常用的方法是检查“项目”-“属性”-“配置属性”-“常规”-“输出目录”里的路径 项目”-“属性”-“配置属性”-“链接器”-“常规”-“输出文件”里的路径,是否一致, ...