02. Implement Atoi
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
I have implemented the Atoi function using a simple iteration through the input string. Here's a breakdown of the steps:
Initialize a variable n
to store the converted integer.
Iterate through the characters of the string.
If it's the first character and it's a '-', skip it since it represents a negative number.
If the character is a digit, update n
by multiplying it by 10 and adding the digit.
If the character is not a digit, return -1 as the input is invalid.
Return the final integer, considering the sign.
Time Complexity: O(N), where N is the length of the input string. We iterate through the string once.
Auxiliary Space Complexity: O(1), as we use a constant amount of space for variables.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.