8. String to Integer (atoi) Medium

@problem@discussion
#String



1/**
2 * [8] String to Integer (atoi)
3 *
4 * Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer
5 * (similar to C/C++'s atoi function).
6 * The algorithm for myAtoi(string s) is as follows:
7 * <ol>
8 * Read in and ignore any leading whitespace.
9 * Check if the next character (if not already at the end of the string) is '-' or '+'. 
10 * Read this character in if it is either. This determines if the final result is negative
11 * or positive respectively. Assume the result is positive if neither is present.
12 * Read in next the characters until the next non-digit charcter or the end of the input
13 * is reached. The rest of the string is ignored.
14 * Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits
15 * were read, then the integer is 0. Change the sign as necessary (from step 2).
16 * If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then
17 * clamp the integer so that it remains in the range. Specifically, integers less
18 * than -2^31 should be clamped to -2^31, and integers greater than 2^31 - 1 should be clamped to 2^31 - 1.
19 * Return the integer as the final result.
20 * </ol>
21 * Note:
22 * 
23 * Only the space character ' ' is considered a whitespace character.
24 * Do not ignore any characters other than the leading whitespace or the rest of
25 * the string after the digits.
26 * 
27 *  
28 * Example 1:
29 * 
30 * Input: s = "42"
31 * Output: 42
32 * Explanation: The underlined characters are what is read in, the caret is the
33 * current reader position.
34 * Step 1: "42" (no characters read because there is no leading whitespace)
35 *          ^
36 * Step 2: "42" (no characters read because there is neither a '-' nor '+')
37 *          ^
38 * Step 3: "<u>42</u>" ("42" is read in)
39 *            ^
40 * The parsed integer is 42.
41 * Since 42 is in the range [-2^31, 2^31 - 1], the final result is 42.
42 * 
43 * Example 2:
44 * 
45 * Input: s = "   -42"
46 * Output: -42
47 * Explanation:
48 * Step 1: "<u>   </u>-42" (leading whitespace is read and ignored)
49 *             ^
50 * Step 2: "   <u>-</u>42" ('-' is read, so the result should be negative)
51 *              ^
52 * Step 3: "   -<u>42</u>" ("42" is read in)
53 *                ^
54 * The parsed integer is -42.
55 * Since -42 is in the range [-2^31, 2^31 - 1], the final result is -42.
56 * 
57 * Example 3:
58 * 
59 * Input: s = "4193 with words"
60 * Output: 4193
61 * Explanation:
62 * Step 1: "4193 with words" (no characters read because there is no leading whitespace)
63 *          ^
64 * Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
65 *          ^
66 * Step 3: "<u>4193</u> with words" ("4193" is read in; reading stops because the next character is a non-digit)
67 *              ^
68 * The parsed integer is 4193.
69 * Since 4193 is in the range [-2^31, 2^31 - 1], the final result is 4193.
70 * 
71 * Example 4:
72 * 
73 * Input: s = "words and 987"
74 * Output: 0
75 * Explanation:
76 * Step 1: "words and 987" (no characters read because there is no leading whitespace)
77 *          ^
78 * Step 2: "words and 987" (no characters read because there is neither a '-' nor '+')
79 *          ^
80 * Step 3: "words and 987" (reading stops immediately because there is a non-digit 'w')
81 *          ^
82 * The parsed integer is 0 because no digits were read.
83 * Since 0 is in the range [-2^31, 2^31 - 1], the final result is 0.
84 * 
85 * Example 5:
86 * 
87 * Input: s = "-91283472332"
88 * Output: -2147483648
89 * Explanation:
90 * Step 1: "-91283472332" (no characters read because there is no leading whitespace)
91 *          ^
92 * Step 2: "<u>-</u>91283472332" ('-' is read, so the result should be negative)
93 *           ^
94 * Step 3: "-<u>91283472332</u>" ("91283472332" is read in)
95 *                      ^
96 * The parsed integer is -91283472332.
97 * Since -91283472332 is less than the lower bound of the range [-2^31, 2^31 - 1], the 
98 * final result is clamped to -2^31 = -2147483648.<span style="display: none;"> </span>
99 * 
100 *  
101 * Constraints:
102 * 
103 * 0 <= s.length <= 200
104 * s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.
105 * 
106 */
107pub struct Solution {}
108
109// problem: https://leetcode.com/problems/string-to-integer-atoi/
110// discuss: https://leetcode.com/problems/string-to-integer-atoi/discuss/?currentPage=1&orderBy=most_votes&query=
111
112// submission codes start here
113
114impl Solution {
115    pub fn my_atoi(s: String) -> i32 {
116        let chs: Vec<char> = s.chars().collect();
117        let mut i = 0;
118        let mut negative = false;
119        let mut result: i64 = 0;
120
121        while i < chs.len() {
122            if chs[i] == ' ' {
123                i += 1;
124                continue;
125            }
126
127            if chs[i] == '-' {
128                negative = true;
129                i += 1;
130                break;
131            } else if chs[i] == '+' {
132                negative = false;
133                i += 1;
134                break;
135            }
136
137            if !chs[i].is_numeric() {
138                return 0;
139            } else {
140                break
141            }
142        }
143
144        while i < chs.len() {
145            if chs[i].is_numeric() {
146                result = result * 10 + chs[i] as i64 - '0' as i64;
147                if !negative && result > i32::MAX as i64 {
148                    return i32::MAX;
149                } else if negative && -result < i32::MIN as i64 {
150                    return i32::MIN;
151                }
152                i += 1;
153            } else {
154                break;
155            }
156        }
157
158        if negative {
159            result = -result;
160        }    
161
162        if result > i32::MAX as i64 {
163            i32::MAX
164        } else if result < i32::MIN as i64 {
165            i32::MIN
166        } else {
167            result as i32
168        }
169    }
170}
171
172// submission codes end
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn test_8() {
180        assert_eq!(Solution::my_atoi("12344".to_string()), 12344);
181        assert_eq!(Solution::my_atoi("   -12344".to_string()), -12344);
182        assert_eq!(Solution::my_atoi("  s +12344".to_string()), 0);
183        assert_eq!(Solution::my_atoi("   +12344".to_string()), 12344);
184        assert_eq!(Solution::my_atoi("   +12344s3".to_string()), 12344);
185        assert_eq!(Solution::my_atoi("   +-112344s3".to_string()), 0);
186        assert_eq!(Solution::my_atoi("9223372036854775808".to_string()), i32::MAX);
187        assert_eq!(Solution::my_atoi("-9223372036854775808".to_string()), i32::MIN);
188        assert_eq!(Solution::my_atoi((i32::MAX as i64 + 11).to_string()), i32::MAX);
189    }
190}
191


Back
© 2025 bowen.ge All Rights Reserved.