随笔- 509  文章- 0  评论- 151  阅读- 22万 

String to Integer (atoi)

2014.2.10 02:23

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

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.

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.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Solution:

  atoi() is a function declared in <stdio.h>, which converts a C-style string to integer. The "Requirements for atoi" has specified every detail you need before starting coding. Actually you shouldn't expect such detailed specification in written text, but from the mouth of the interviewer, when you're facing a real technical interview.

  The next job is to finish the problem with your code being as simple as possible. Perhaps I could do better, but this one below is enough to get an AC from LeetCode OJ.

  Note that the conversion ends when an invalid character is encountered.

  Time complexity is O(n), where n is the length of the string. Space complexity is O(1).

Accepted code:

复制代码
 1 // 2CE, 1RE, 1TLE, 2WA, 1AC, never write your code in a hurry.
 2 #include <climits>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     int atoi(const char *str) {
 9         int i, len;
10         int flag;
11         long long int result = 0;
12         
13         if (str == NULL) {
14             return result;
15         } else if (str[i] == '-') {
16             flag = -1;
17             ++i;
18         } else if (str[i] == '+') {
19             flag = +1;
20             ++i;
21         } else {
22             flag = +1;
23         }
24         
25         long long int int_min, int_max;
26         
27         int_min = INT_MIN;
28         int_max = INT_MAX;
29         while (i < len) {
30             if (s[i] >= '0' && s[i] < '9') {
31                 result = result * 10 + (s[i] - '0');
32                 if (flag == -1) {
33                     if (-result < int_min) {
34                         // underflow
35                         return int_min;
36                     }
37                 } else {
38                     if (result > int_max) {
39                         // overflow
40                         return int_max;
41                     }
42                 }
43             }
44             ++i;
45         }
46         
47         return flag * result;
48     }
49 };
复制代码

 

 posted on   zhuli19901106  阅读(197)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示