当前位置:网站首页>leetcode-8. String to integer (ATOI)
leetcode-8. String to integer (ATOI)
2022-06-25 15:52:00 【Grey wolf learns Java】
JAVA solution
class Solution {
public int myAtoi(String s) {
// Convert the string passed in to a character array
char[] chars = s.toCharArray();
// Gets the length of the character array
int n = chars.length;
// Define the starting position of the global index
int idx = 0;
while (idx < n && chars[idx] == ' ') {
// Remove space
idx++;
}
if (idx == n) {
// After removing all spaces, stop the program if it reaches the end
return 0;
}
// Whether the tag is negative
boolean negative = false;
if (chars[idx] == '-') {
// Negative sign encountered , Is marked as negative
negative = true;
// Go on to the next
idx++;
} else if (chars[idx] == '+') {
// Encounter a plus sign , Then go straight to the next
idx++;
} else if (!Character.isDigit(chars[idx])) {
// If the first one encounters other characters that are not numbers or signs, stop the program
return 0;
}
// Define a variable that stores the final result
int ans = 0;
// When the array subscript does not exceed the bounds and the characters are numbers, the traversal is performed
while (idx < n && Character.isDigit(chars[idx])) {
// Due to character '0' To '9' Of ASCII Value is continuous , By character ASCII Value difference can be cleverly converted to the integer value corresponding to the character
int digit = chars[idx] - '0';
// Every cycle should prevent overflow caused by too large value , To judge ans * 10 + digit Is it greater than Integer.MAX_VALUE, But directly ans * 10 + digit May overflow here directly , So in order to avoid overflow during operation , Shift the equation , Change multiplication into division
if (ans > (Integer.MAX_VALUE - digit) / 10) {
// If it is judged that the number is negative , return Integer.MIN_VALUE, If it is positive, it returns ,Integer.MAX_VALUE
return negative? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
// Because traversal is from left to right , So just use it every time ans multiply 10 Add the current value to restore the value corresponding to the number
ans = ans * 10 + digit;
// next
idx++;
}
// Return the final result , If it is regular, it returns a positive number , If it is negative, it returns a negative number
return negative? -ans : ans;
}
}Problem analysis
According to the requirements of the topic , This problem is to extract the number in the string passed in and convert it into its corresponding value , The title tells you that the target number may have positive and negative signs , And there are spaces and other non numeric characters in the string .
First, we split the incoming string into characters one by one and store them in the character array , And record the array length , Define the starting position of the global index as 0, Then we use while Loop to remove all leading spaces ( skip ), Determine the position of the global index after removing spaces , If the position of the global index comes to the end of the string , It means that the string is pure space , Terminate program execution .
If the position of the global index is less than the end position of the string, it will be executed downward , First define a Boolean value to mark whether the target number is negative , The default is false, Is a negative number true Otherwise false. here , Intercept the character of the current global index to determine whether it is a negative sign 、 Plus sign or other non numeric characters , If it is a minus sign , Set the Boolean value to true, And move the global index to the next character position , If it is a positive sign , Then go directly to the next position ( Unsigned defaults to positive ), Assuming other non numeric characters, the program will be terminated directly .
First define a variable to store the final result , If the character after the sign bit is a numeric character ( Or the first character is not a sign bit and is a numeric character ), Then enter the cycle , Within the bounds of the array length , Put all the resulting numeric characters (‘0’-‘9’) Respectively with character 0 namely ‘0’ Make a difference , Due to character '0' To '9' Of ASCII Value is continuous , By character ASCII Value difference can be cleverly converted to the integer value corresponding to the character , Every cycle should prevent overflow caused by too large value , To judge ans * 10 + digit Is it greater than Integer.MAX_VALUE, But directly ans * 10 + digit May overflow here directly , So in order to avoid overflow during operation , Shift the equation , Change multiplication into division .
If it is greater than the integer maximum value, the integer maximum value or the integer minimum value will be returned according to the positive and negative of the number , If the operation does not exceed the maximum value of an integer , Then continue to accumulate the final result , Because traversal is from left to right , So just use it every time ans multiply 10 Add the current value to restore the value corresponding to the number , Continue to move the global index until it is equal to the length of the array, and jump out of the loop , Return the final result according to the positive or negative of the target number .
leetcode The original title is :8. String conversion integers (atoi)
边栏推荐
- Check whether the port number is occupied
- 不要再「外包」AI 模型了!最新研究发现:有些破坏机器学习模型安全的「后门」无法被检测到
- 元宇宙系统的概念解析
- 教务系统开发(PHP+MySQL)
- Is it safe to open a stock account in Guoxin golden sun?
- Read the configuration, explain the principle and read the interview questions. I can only help you here...
- JVM memory region details
- Client development (electron) system level API usage
- Optimization of lazyagg query rewriting in parsing data warehouse
- Rapport de la main - d'oeuvre du Conseil de développement de l'aecg air32f103cbt6
猜你喜欢
After the project is pushed to the remote warehouse, Baota webhook automatically publishes it

剑指 Offer 06. 从尾到头打印链表

读配置、讲原理、看面试真题,我只能帮你到这了。。。
Why is it said that restarting can solve 90% of the problems

地理位置数据存储方案——Redis GEO

Report on Hezhou air32f103cbt6 development board

Continuous integration of aspnetcore & cloud flow

《睡眠公式》:怎么治睡不好?

Highly concurrent optimized Lua + openresty+redis +mysql (multi-level cache implementation) + current limit +canal synchronization solution

剑指 Offer 07. 重建二叉树
随机推荐
f_read 函数[通俗易懂]
sql优化的几种方式
Internal class learning notes
Differences and solutions of redis cache avalanche, cache penetration and cache breakdown
Startup and shutdown of appium service
Leetcode topic [array]-34- find the first and last positions of elements in a sorted array
JVM memory region details
剑指 Offer 05. 替换空格
[issue 24] one year experience of golang to develop futu
LeCun预言AGI:大模型和强化学习都是斜道!我的「世界模型」才是新路
Sword finger offer 09 Implementing queues with two stacks
Why is it said that restarting can solve 90% of the problems
Mapbox map - inconsistent coordinate system when docking GIS layers?
js 给元素添加自定义属性
Analysis of the concept of metacosmic system
What is the safest app for stock account opening? Tell me what you know
Describe your understanding of the evolution process and internal structure of the method area
Client development (electron) system level API usage 2
Constructor Pattern
Write one file to the marked location of another file