当前位置:网站首页>LeetCode 8. String to integer (ATOI) (medium, string)
LeetCode 8. String to integer (ATOI) (medium, string)
2022-06-11 00:50:00 【Grilled little fat sheep with charcoal...】
Title Description : Please come to realize a myAtoi(string s) function , Enable it to convert a string to a 32 Bit signed integer ( similar C/C++ Medium atoi function ).
function myAtoi(string s) The algorithm is as follows :
1. Read in strings and discard useless leading spaces
2. Check the next character ( Suppose you haven't reached the end of the character yet ) Positive or negative , Read the character ( If there is ). Determine whether the final result is negative or positive . If neither exists , Suppose the result is positive .
3. Read in the next character , Until you reach the next non numeric character or the end of the input . The rest of the string will be ignored .
4. Convert the numbers read in the previous steps into integers ( namely ,"123" -> 123, "0032" -> 32). If you don't read in the numbers , Then the integer is 0 . Change the symbol if necessary ( From step 2 Start ).
If the number of integers exceeds 32 Bit signed integer range [−231, 231 − 1] , You need to truncate this integer , Keep it in this range . say concretely , Less than −231 The integer of should be fixed to −231 , Greater than 231 − 1 The integer of should be fixed to 231 − 1 .
5. Returns an integer as the final result .
Be careful :
The white space character in this question only includes the space character ' ' .
Except for the leading space or the rest of the string after the number , Do not ignore Any other character .
Example 1:
Input :s = "42"
Output :42
explain : The bold string is the character that has been read in , The caret is the character currently read .
The first 1 Step :"42"( No characters are currently read in , Because there are no leading spaces )
^
The first 2 Step :"42"( No characters are currently read in , Because it doesn't exist here '-' perhaps '+')
^
The first 3 Step :"42"( Read in "42")
^
Parse to get an integer 42 .
because "42" In scope [-231, 231 - 1] Inside , The final result is 42 .
Example 2:
Input :s = " -42"
Output :-42
explain :
The first 1 Step :" -42"( Read in leading space , But ignore )
^
The first 2 Step :" -42"( Read in '-' character , So the result should be negative )
^
The first 3 Step :" -42"( Read in "42")
^
Parse to get an integer -42 .
because "-42" In scope [-231, 231 - 1] Inside , The final result is -42 .
Example 3:
Input :s = "4193 with words"
Output :4193
explain :
The first 1 Step :"4193 with words"( No characters are currently read in , Because there are no leading spaces )
^
The first 2 Step :"4193 with words"( No characters are currently read in , Because it doesn't exist here '-' perhaps '+')
^
The first 3 Step :"4193 with words"( Read in "4193"; Because the next character is not a number , So read in stop )
^
Parse to get an integer 4193 .
because "4193" In scope [-231, 231 - 1] Inside , The final result is 4193 .
Tips :
0 <= s.length <= 200
s By the English letters ( Uppercase and lowercase )、 Numbers (0-9)、' '、'+'、'-' and '.' form
Code implementation :
public static int myAtoi(String s){
if(s.length() == 0){
return 0;
}
int index = 0; // Traverse to the current character position
long res = 0; // final result
int sign = 1; // 1 Is an integer , -1 It's a negative number
int length = s.length(); // The length of the array
// Remove spaces logically
while (index < length && s.charAt(index) == ' '){
index++;
}
if(index == length){
return 0;
}
// Judging symbols
if(s.charAt(index) == '-' || s.charAt(index) == '+'){
sign = s.charAt(index++) == '+' ? 1 : -1;
}
for (; index < length; index++) {
int digit = s.charAt(index) - '0';
if(digit < 0 || digit > 9){
// If it is not a number, exit directly
break;
}
res = res * 10 + digit;
// If the maximum value is exceeded , Return the maximum value directly
if(res * sign > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
// If it's less than the minimum , Return the minimum value directly
if(res * sign < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
}
return (int) (sign * res);
}
source : Power button (LeetCode)
link :https://leetcode.cn/problems/string-to-integer-atoi
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
边栏推荐
- C语言实现设置桌面壁纸
- Using solrj to add, delete, modify, and query Solr is too simple
- Computer screen recording free software GIF and other format videos
- How word inserts a guide (dot before page number) into a table of contents
- MESI cache consistency protocol for concurrent programming
- [network planning] 2.2.4 Web cache / proxy server
- compiler explorer
- Random points in non overlapping rectangles
- Canvas drawing line break
- 循环结构语句
猜你喜欢

Lucene mind map makes search engines no longer difficult to understand

Deploy netron services through kubernetes and specify model files at startup

Complete collection of MySQL exercises (with answers) - you will know everything after practice

MySQL

Décomposition détaillée du problème de chemin le plus court du graphique

适配器模式

图的最短路径问题 详细分解版

How word removes the header line

【无标题】4555

Synchronized keyword for concurrent programming
随机推荐
On the quality assurance system of youzan search V2021
系统应用安装时,签名校验失败问题
ts+fetch实现选择文件上传
Multipass Chinese document - Overview
Pirate OJ 448 luck draw
Room第一次使用
QT program plug-in reports an error plugin xcb
C语言实现设置桌面壁纸
Canvas drawing line break
UUID quick explanation
How word inserts a guide (dot before page number) into a table of contents
12324243242
[no title] 4555
Wechat applet to realize OCR scanning recognition
阻塞队列 — DelayedWorkQueue源码分析
JVM garbage collection mechanism and common garbage collectors
Unity custom folder icon color personalized unity compiler
Pirate OJ 148 String inversion
With a market value of 21.5 billion yuan, will the post-80s generation in Sichuan make TV history?
Pirate OJ 146 character string