当前位置:网站首页>8. Go implementation of string conversion integer (ATOI) and leetcode
8. Go implementation of string conversion integer (ATOI) and leetcode
2022-07-04 00:26:00 【Li Jue】
8. String conversion integers (atoi)
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 :
Read in strings and discard useless leading spaces
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 .
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 .
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 .
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
Traverse : Simulation is enough
func myAtoi(s string) int {
// Traverse
s = strings.TrimSpace(s)
result := 0
flag := 1
for i, v := range s {
if v >= '0' && v <= '9' {
result = result*10 + int(v-'0')
} else if v == '-' && i == 0 {
flag = -1
} else if v == '+' && i == 0 {
flag = 1
} else {
break
}
if result > math.MaxInt32 {
if flag == -1 {
return math.MinInt32
}
return math.MaxInt32
}
}
return flag * result
}边栏推荐
- Gossip about redis source code 76
- Is the securities account opened by Caicai for individuals safe? Is there a routine
- The upload experience version of uniapp wechat applet enters the blank page for the first time, and the page data can be seen only after it is refreshed again
- STM32 GPIO CSDN creative punch in
- Iclr2022: how does AI recognize "things I haven't seen"?
- Detailed explanation of the relationship between Zhongtai, wechat and DDD
- Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
- Stock price forecast
- MySQL 8.0.12 error: error 2013 (HY000): lost connection to MySQL server during query
- Test the influence of influent swacth on the electromagnetic coil of quartz meter
猜你喜欢

Struct in linked list
![[NLP] text classification still stays at Bert? Duality is too strong than learning framework](/img/49/1ff6025bdb0445e5638c1451e0b267.jpg)
[NLP] text classification still stays at Bert? Duality is too strong than learning framework

STM32 key light

Briefly understand the operation mode of developing NFT platform

Iclr2022: how does AI recognize "things I haven't seen"?

Celebrate the new year | Suihua fire rescue detachment has wonderful cultural activities during the Spring Festival

BBS forum recommendation

Is user authentication really simple

Analysis on the scale of China's smart health industry and prediction report on the investment trend of the 14th five year plan 2022-2028 Edition
![[source code] VB6 chat robot](/img/89/46b67f627c8257eaddc70a247c9ba5.jpg)
[source code] VB6 chat robot
随机推荐
It is forbidden to splice SQL in code
SQL data update
Cannot build artifact 'test Web: War expanded' because it is included into a circular depend solution
What is the future of software testing industry? Listen to the test veterans' answers
Att & CK actual combat series - red team actual combat - V
Data mining vs Machine Learning: what is the difference between them? Which is more suitable for you to learn
想请教一下,十大劵商如何开户?在线开户是安全么?
The difference between objects and objects
China standard gas market prospect investment and development feasibility study report 2022-2028
NLP pre training technology development
Private project practice sharing populate joint query in mongoose makes the template unable to render - solve the error message: syntaxerror: unexpected token r in JSON at
A method to solve Bert long text matching
Global and Chinese markets for instant saliva testing devices 2022-2028: Research Report on technology, participants, trends, market size and share
Is user authentication really simple
Global and Chinese market of glossometer 2022-2028: Research Report on technology, participants, trends, market size and share
Anomalies seen during the interview
Gossip about redis source code 80
Alibaba test engineer with an annual salary of 500000 shares notes: a complete set of written tests of software testing
Solve the problem that the kaggle account registration does not display the verification code
Correlation analysis summary