String To Integer (atoi)

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 79 :-  String To Integer (atoi)

Converting a string to an integer, also known as the "atoi" (ASCII to Integer) problem, is a common coding interview question. The task is to convert a given string containing digits (and optional leading whitespace and sign) to its corresponding integer representation.

Here are the steps to implement the atoi function:

Remove leading whitespace from the string.

Check if the first non-whitespace character is a sign (+ or -). If it is, keep track of the sign of the integer.

Iterate through the remaining characters of the string until a non-digit character is encountered or until the end of the string.

Convert the consecutive digits into an integer, making sure to handle integer overflow.

Return the resulting integer, considering the sign we kept track of earlier.

Here's a Python function to implement atoi:

pythonCopy code

def atoi(s):    # Remove leading whitespace    s = s.strip()    # Check for empty string or invalid input    if not s or (not s[0].isdigit() and s[0] not in ['+', '-']):        return 0    # Check for the sign    sign = 1    if s[0] == '-':        sign = -1        s = s[1:]    elif s[0] == '+':        s = s[1:]    # Convert the digits to an integer    result = 0    for char in s:        if char.isdigit():            result = result * 10 + int(char)        else:            break    # Apply the sign and handle integer overflow    result = max(min(sign * result, 2**31 - 1), -2**31)    return result # Example usage: input_str = "   -42" output_int = atoi(input_str) print(output_int)

Output:

diffCopy code

-42

In this example, the function atoi takes the input string s, processes it according to the steps mentioned above, and returns the resulting integer. The function handles leading whitespace, signs, and invalid inputs. It also takes care of integer overflow, ensuring the result falls within the range of a 32-bit signed integer (between -2^31 to 2^31 - 1).

11. Week5 - Assignments

2 Comments

@mk.info.work
mk.info.work Feb 17, 2024 at 10:20 PM

SCIAKU Team please upload 1st video of TREE please please please, please

@na3744
na3744 Feb 23, 2024 at 2:52 AM

I bought this course, it worth it!

@mk.info.work
mk.info.work Nov 15, 2023 at 10:25 PM

Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it

@sciaku1
sciaku1 Jan 11, 2024 at 3:23 PM

Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support