Problem Statement
Implement the myAtoi(string s)
function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s) is as follows:
- Whitespace: Ignore any leading whitespace (" ").
- Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present.
- Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
- Rounding: If the integer is out of the 32-bit signed integer range
[-2^31, 2^31 - 1]
, then round the integer to remain in the range. Specifically, integers less than-2^31
should be rounded to-2^31
, and integers greater than2^31 - 1
should be rounded to2^31 - 1
.
Return the integer as the final result.
Examples
Example 1:
Different Approaches
1️⃣ Iteration
Code:
#include <climits>
#include <string>
using namespace std;
class Solution {
public:
int myAtoi(string s) {
// Initialize variables
int index = 0; // Pointer to traverse the string
int length = s.length(); // Length of the input string
int result = 0; // Holds the final integer value
bool isNegative = false; // Flag to determine if the number is negative
// Step 1: Skip leading whitespaces
while (index < length && s[index] == ' ') {
index++;
}
// Step 2: Check for a sign
if (index < length && (s[index] == '-' || s[index] == '+')) {
isNegative = (s[index] == '-');
index++;
}
// Step 3: Convert digits to integer
while (index < length && s[index] >= '0' && s[index] <= '9') {
int digit = s[index] - '0';
// Step 4: Handle overflow
if (result > (INT_MAX - digit) / 10) {
return isNegative ? INT_MIN : INT_MAX;
}
result = result * 10 + digit;
index++;
}
// Step 5: Apply the sign
return isNegative ? -result : result;
}
};