String to Integer (atoi) - CPP Solution

1. Introduction

This blog post focuses on the implementation of the myAtoi(string s) function, a common task in C++ programming that involves converting a string to a 32-bit signed integer. The function mimics the behavior of C/C++'s atoi function, and it's a great example to understand string parsing and edge case handling in programming.

Problem

The task is to implement the myAtoi(string s) function to convert a string into a 32-bit signed integer, following these steps:

1. Ignore leading whitespaces.

2. Check for a '+' or '-' sign indicating the sign of the number.

3. Read characters until a non-digit is found or the end of the string is reached.

4. Convert the digits into an integer and apply the sign.

5. Clamp the integer to the 32-bit signed integer range [-2^31, 2^31 - 1].

6. Return the final integer.

2. Solution Steps

1. Start by trimming leading white spaces from the string.

2. Check the first non-space character for a '+' or '-' sign.

3. Iterate through the string and process each digit.

4. Build the integer by multiplying the current number by 10 and adding the new digit.

5. Handle overflows by clamping the result to the 32-bit integer limits.

6. Return the final integer with the appropriate sign.

3. Code Program

#include <iostream>
#include <climits>
using namespace std;

// Function to convert string to an integer, mimicking the atoi function
int myAtoi(string s) {
    int i = 0, sign = 1;
    long result = 0; // Use long to handle overflow

    // Ignore leading whitespaces
    while (i < s.size() && s[i] == ' ') i++;

    // Check for sign
    if (i < s.size() && (s[i] == '+' || s[i] == '-')) {
        sign = (s[i] == '-') ? -1 : 1;
        i++;
    }

    // Convert string to integer
    while (i < s.size() && isdigit(s[i])) {
        result = result * 10 + (s[i] - '0');

        // Check for overflow and clamp if necessary
        if (sign == 1 && result > INT_MAX) return INT_MAX;
        if (sign == -1 && -result < INT_MIN) return INT_MIN;
        i++;
    }

    return result * sign; // Apply sign
}

int main() {
    string str = "   -42";
    cout << "Converted integer: " << myAtoi(str) << endl;
    return 0;
}

Output:

Converted integer: -42

Explanation:

1. The input string " -42" starts with whitespaces and a negative sign.

2. Whitespaces are ignored, and the negative sign is noted.

3. Each digit is processed to build the integer part.

4. The number '-42' is within the 32-bit signed integer range, so no clamping is needed.

5. The final integer, '-42', is returned as the output.


Comments