-
-
Notifications
You must be signed in to change notification settings - Fork 99
Closed
Labels
hacktoberest-acceptedhacktoberfest-acceptedhacktoberfest-acceptedhacktoberfesthacktoberfesthacktoberfestmediumMedium Level QuestionMedium Level Question
Description
Problem Number
8
Problem Title
String to Integer (atoi)
LeetCode Link
https://leetcode.com/problems/string-to-integer-atoi/description/
Contribution Checklist
- I have written the Approach section.
- I have written the Intuition section.
- I have included a working C++ solution.
- I will raise a PR and ensure the filename follows the convention
[Number]. [Problem Title].cpp.
Approach
-
Skip Extra Spaces:
First, move through the string and ignore all spaces at the beginning.
We only start reading when we find a number or a sign (+or-).
- Check the Sign:
- If the next character is
'-', we mark the number as negative. - If it’s
'+', we keep it as positive. - Then, move to the next character.
- Read the Digits:
- Go through each character while it’s a number (
'0'–'9'). - Convert it to an integer using
s[i] - '0'. - Add it to our result using
ans = ans * 10 + digit.
- Check for Overflow / Underflow:
- If the number becomes bigger than
INT_MAX (2³¹ − 1), stop and returnINT_MAX. - If it becomes smaller than
INT_MIN (−2³¹), returnINT_MIN.
This keeps the value within the valid integer range.
- Return the Final Number:
Multiply the result by the sign (+1or-1) and return it.
Time Complexity: O(n) - we go through the string once.
Space Complexity: O(1).
Intuition
This problem works like the C function atoi(), where we convert a string into an integer manually.
Note : atoi stands for ASCII to Integer
We simply:
- Skip all spaces at the start.
- Check if there’s a
+or-sign.. - Read the digits one by one until a non-digit appears.
- Stop if the number goes beyond the integer range.
The idea is to build the number step by step, just like how a program reads and converts text into numbers.
Solution in C++
class Solution {
public:
int myAtoi(string s) {
int l = s.length();
int sign = 1, i = 0;
long long ans = 0;
// trimming leading spaces
while (i < l && s[i] == ' ') i++;
// sign check condition
if (i == l)
return 0;
if (s[i] == '-') {
sign = -1;
i++;
} else if (s[i] == '+')
i++;
// converting characters to integer
while (i < l && isdigit(s[i])) {
int digit = s[i] - '0';
ans = ans * 10 + digit;
// overflow condition handling
if (sign == 1 && ans > INT_MAX) {
return INT_MAX;
}
if (sign == -1 && (-1 * ans) < INT_MIN) {
return INT_MIN;
}
i++;
}
return (int)(ans * sign);
}
};Metadata
Metadata
Assignees
Labels
hacktoberest-acceptedhacktoberfest-acceptedhacktoberfest-acceptedhacktoberfesthacktoberfesthacktoberfestmediumMedium Level QuestionMedium Level Question