当前位置:网站首页>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
}边栏推荐
- Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
- China standard gas market prospect investment and development feasibility study report 2022-2028
- Investment demand and income forecast report of China's building ceramics industry, 2022-2028
- Idea set class header comments
- Alibaba test engineer with an annual salary of 500000 shares notes: a complete set of written tests of software testing
- Struct in linked list
- Global and Chinese markets of distributed control system (DCS) consumption 2022-2028: Research Report on technology, participants, trends, market size and share
- 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
- CSP window
- Several ways to set up a blog locally [attach relevant software download links]
猜你喜欢

(Video + graphics and text) introduction to machine learning series - Chapter 4 naive Bayes

The difference between objects and objects

2022 system integration project management engineer examination knowledge points: software development model

Vscode regular match replace console log(.*)

Cannot build artifact 'test Web: War expanded' because it is included into a circular depend solution

Entropy and full connection layer

Alibaba cloud container service differentiation SLO hybrid technology practice
![Docking Alipay process [pay in person, QR code Payment]](/img/30/665580241020ee3adb872e725f0624.jpg)
Docking Alipay process [pay in person, QR code Payment]

Tencent interview: can you find the number of 1 in binary?

SPI based on firmware library
随机推荐
It is the most difficult to teach AI to play iron fist frame by frame. Now arcade game lovers have something
Cannot build artifact 'test Web: War expanded' because it is included into a circular depend solution
SQL data update
Social network analysis -social network analysis
Double efficiency. Six easy-to-use pychar plug-ins are recommended
Struct in linked list
Reading notes on how programs run
I wrote a chat software with timeout connect function
leetcode-43. String multiplication
Yyds dry goods inventory three JS source code interpretation - getobjectbyproperty method
Development and application of fcitx functional plug-ins
CSP window
Introducing Software Testing
What is the potential of pocket network, which is favored by well-known investors?
Report on prospects and future investment recommendations of China's assisted reproductive industry, 2022-2028 Edition
What is the Valentine's Day gift given by the operator to the product?
ESP Arduino playing with peripherals (V) basic concept of interrupt and timer interrupt
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
NLP Chinese corpus project: large scale Chinese natural language processing corpus
Qtcharts notes (V) scatter diagram qscatterseries