Leetcode 8. String to Integer (atoi)
Problem Explanation:
The problem is asking us to implement a function that converts a given string into an integer. It involves three steps:
-
Trimming the whitespace from both sides of the string (Trimming is removing all leading and trailing spaces).
-
Extracting the sign (if present) of the number, which could be
+
or-
. If no sign is present, assume it is positive. -
Multiplying each digit in the string by a power of 10, starting from the least significant digit on the right and moving to the left, accumulating the total at each step. If while doing this, the number exceeds the range of a 32-bit integer, we have to return the maximum or minimum value for a 32-bit integer (depending on the sign).
For example:
If the input string is " -123 "
, the function should return -123
.
In this example, the function first trims the whitespace, getting "-123"
. It then extracts the negative sign, and multiplies each digit by a power of 10 to get the number 123
. Since the sign is negative, it then finally applies the sign to get the result -123
.
Approach of the Solution:
The solution applies the steps as described in the explanation above.
-
Trimming is done using a utility method that makes use of built-in string methods.
-
Before multiplying the digits by 10, it first checks if the character in the string is a digit using the built-in
isdigit()
function. If the character is not a digit, it breaks from the loop. -
It checks if the number is within the range of a 32-bit integer at each iteration. If it is not, it returns the maximum or minimum 32-bit integer value depending on the sign.
Python Solution:
1 2python 3class Solution: 4 def myAtoi(self, s: str) -> int: 5 6 # Remove leading and trailing spaces 7 s = s.lstrip().rstrip() 8 9 if not s: 10 return 0 11 12 sign = -1 if s[0] == '-' else 1 13 if s[0] in '+-': 14 s = s[1:] 15 16 num = 0 17 for c in s: 18 if not c.isdigit(): 19 break 20 num = num * 10 + int(c) 21 22 # Check if number is within the 32-bit integer range 23 if sign * num < -2147483648: 24 return -2147483648 25 if sign * num > 2147483647: 26 return 2147483647 27 28 return sign * num 29 30
Java Solution:
1
2java
3class Solution {
4 public int myAtoi(String s) {
5
6 // Remove leading and trailing spaces
7 s = s.trim();
8
9 if (s.isEmpty()) {
10 return 0;
11 }
12
13 int sign = s.charAt(0) == '-' ? -1 : 1;
14 if (s.charAt(0) == '+' || s.charAt(0) == '-') {
15 s = s.substring(1);
16 }
17
18 long num = 0;
19 for (char c : s.toCharArray()) {
20 if (!Character.isDigit(c)) {
21 break;
22 }
23 num = num * 10 + (c - '0');
24
25 // Check if number is within the 32-bit integer range
26 if (sign * num < Integer.MIN_VALUE) {
27 return Integer.MIN_VALUE;
28 }
29 if (sign * num > Integer.MAX_VALUE) {
30 return Integer.MAX_VALUE;
31 }
32 }
33
34 return (int) (sign * num);
35 }
36}
Javascript Solution:
1 2javascript 3class Solution { 4 myAtoi(s) { 5 6 // Remove leading and trailing spaces 7 s = s.trim(); 8 9 if (!s) { 10 return 0; 11 } 12 13 let sign = s[0] === '-' ? -1 : 1; 14 if (s[0] === '+' || (s[0] === '-')) { 15 s = s.slice(1); 16 } 17 18 let num = 0; 19 for (let i = 0; i < s.length; ++i) { 20 let char = s[i]; 21 if (isNaN(char)) { 22 break; 23 } 24 num = num * 10 + parseInt(char); 25 26 // Check if number is within the 32-bit integer range 27 if (sign * num < 2147483648 * -1) { 28 return 2147483648 * -1; 29 } 30 if (sign * num > 2147483647) { 31 return 2147483647; 32 } 33 } 34 return sign * num; 35 } 36}
C++ Solution:
1
2cpp
3class Solution {
4public:
5 int myAtoi(string s) {
6
7 // Remove leading and trailing spaces
8 s.erase(0, s.find_first_not_of(' '));
9 s.erase(s.find_last_not_of(' ') + 1);
10
11 if (s.empty()) {
12 return 0;
13 }
14
15 int sign = s.at(0) == '-' ? -1 : 1;
16 if (s.at(0) == '+' || s.at(0) == '-') {
17 s = s.substr(1);
18 }
19
20 long num = 0;
21 for (char c : s) {
22 if (!isdigit(c)) {
23 break;
24 }
25 num = num * 10 + (c - '0');
26
27 // Check if number is within the 32-bit integer range
28 if (sign * num < INT_MIN) {
29 return INT_MIN;
30 }
31 if (sign * num > INT_MAX) {
32 return INT_MAX;
33 }
34 }
35
36 return sign * num;
37 }
38};
39
C# Solution:
1
2csharp
3public class Solution {
4 public int MyAtoi(string s) {
5
6 // Remove leading and trailing spaces
7 s = s.Trim();
8
9 if (string.IsNullOrEmpty(s)) {
10 return 0;
11 }
12
13 int sign = s[0] == '-' ? -1 : 1;
14 if (s[0] == '+' || s[0] == '-') {
15 s = s.Substring(1);
16 }
17
18 long num = 0;
19 foreach (char c in s) {
20 if (!char.IsDigit(c)) {
21 break;
22 }
23 num = num * 10 + (c - '0');
24
25 // Check if number is within the 32-bit integer range
26 if (sign * num < int.MinValue) {
27 return int.MinValue;
28 }
29 if (sign * num > int.MaxValue) {
30 return int.MaxValue;
31 }
32 }
33
34 return (int) (sign * num);
35 }
36}
Rust Solution:
1
2rust
3impl Solution {
4 pub fn my_atoi(s: String) -> i32 {
5 let s = s.trim();
6 if s.is_empty() {
7 return 0;
8 }
9
10 let (sign, s) = if s.starts_with('-') {
11 (-1, &s[1..])
12 } else if s.starts_with('+') {
13 (1, &s[1..])
14 } else {
15 (1, s)
16 };
17
18 let mut num: i64 = 0;
19 for c in s.chars() {
20 if !c.is_digit(10) {
21 break;
22 }
23 num = num * 10 + c.to_digit(10).unwrap() as i64 * sign;
24
25 // Check if number is within the 32-bit integer range
26 if num < i32::MIN as i64 {
27 return i32::MIN;
28 }
29 if num > i32::MAX as i64 {
30 return i32::MAX;
31 }
32 }
33 num as i32
34 }
35}
Go Solution:
1
2go
3func myAtoi(s string) int {
4 // Remove leading and trailing spaces
5 s := strings.TrimSpace(s)
6
7 if s == "" {
8 return 0
9 }
10
11 sign := 1
12 if s[0] == '+' || s[0] == '-' {
13 if s[0] == '-' {
14 sign = -1
15 }
16 s = s[1:]
17 }
18
19 num := 0
20 for _, c := range s {
21 if !unicode.IsDigit(c) {
22 break
23 }
24 num = num*10 + int(c - '0')
25
26 // Check if number is within the 32-bit integer range
27 if sign*num < math.MinInt32 {
28 return math.MinInt32
29 }
30 if sign*num > math.MaxInt32 {
31 return math.MaxInt32
32 }
33 }
34
35 return sign * num
36}
In all the above solutions, we first removing the leading and trailing spaces from the string. We then check if the string is empty. If so, we return 0
as there is no number to parse.
We also handle the sign of the number. If the first character of the string is '-'
, we set the sign
to -1
, otherwise we set it to 1
. If the first character is a +
or a -
, we remove it from the string.
We then initialize a variable num
to 0 and loop through each character of the string. If a character is not a digit, we break the loop. If it is a digit, we multiply the current number by 10 and add the integer value of the digit to it.
In each iteration of the loop, we check if the number we have so far (multiplied by its sign) is within the 32-bit integer range. If it is not, we return the maximum or minimum 32-bit integer value depending on the sign.
Finally, we return the number multiplied by its sign which represents its value and sign in integer format.
Got a question?ย Ask the Teaching Assistantย anything you don't understand.
Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.