description:
Implement atoi which converts a string to an integer.
实现string转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.
这个功能首先要去掉在string前面的空格,如果第一个非空的字符是正负号,则要做一个标记,在他的后边要找到尽可能多的数字,然后都转成整形类型。
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.
如果第一个字符既不是正负号也不是数字就stop
If no valid conversion could be performed, a zero value 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.
my answer:
class Solution {
public:
int myAtoi(string str) {
if (str.empty()) return 0; //要考虑string为空的情况
int base = 0, sign = 1, i = 0, n = str.size();
while(i < n && str[i] == ' ') ++i; // i<n must always to think about
if((str[i] == '+' ||str[i] == '-') && i < n){
sign = (str[i++] == '+') ? 1 : -1;
//cause the i in while and not in for ,but it must to add every iteration, so use the i++ to imply the add-one function
}
while(i < n && str[i] >= '0' && str[i] <= '9'){
if(base > INT_MAX/10 || (base == INT_MAX/10 && str[i] - '0' > 7)){
return (sign == 1) ? INT_MAX : INT_MIN;
}
base = base * 10 + (str[i++] - '0');
}
return sign * base;
}
};
relative point get√:
在while循环里还想实现for循环的i++,可以在while的代码段里调用i的时候就用i++,如上面代码里的str[i++]
hint :
关键在于数清可能遇到的可能情况
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· Vite CVE-2025-30208 安全漏洞
· 《HelloGitHub》第 108 期
· MQ 如何保证数据一致性?
· 一个基于 .NET 开源免费的异地组网和内网穿透工具