Skip to content

Conversation

@ayushHardeniya
Copy link
Contributor

@ayushHardeniya ayushHardeniya commented Oct 18, 2025

8. String to Integer (atoi).cpp


Intuition

This problem is basically about turning a string into an integer, like the C function atoi().
My thought process was simple: skip spaces, check the sign, read the digits, and stop at the first non-digit.
Also, we need to make sure the number stays within the int range to avoid overflow or underflow.


Approach

  1. Skip spaces at the start so we only deal with the real number.
  2. Check for '+' or '-' to know if the result should be positive or negative.
  3. Read digits one by one and build the number (ans = ans * 10 + digit).
  4. Handle overflow/underflow: before adding a new digit, check if it goes beyond INT_MAX or below INT_MIN.
  5. Return the result multiplied by the sign.
  • Time Complexity: O(n) - we go through the string once.
  • Space Complexity: O(1) - just a few variables used.

Code Solution (C++)

class Solution {
public:
    int myAtoi(string s) {
        int i = 0, n = s.size(), sign = 1;
        long ans = 0;

        // Skip leading spaces
        while (i < n && s[i] == ' ') i++;

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

        // Build the number
        while (i < n && isdigit(s[i])) {
            int digit = s[i] - '0';

            // Overflow/Underflow check
            if (ans > (INT_MAX - digit) / 10)
                return sign == 1 ? INT_MAX : INT_MIN;

            ans = ans * 10 + digit;
            i++;
        }

        return ans * sign;
    }
};

## Summary by Sourcery

New Features:
- Implement myAtoi that trims leading spaces, detects optional '+' or '-' sign, parses continuous digit characters, and clamps overflow to INT_MAX/INT_MIN in O(n) time and O(1) space

@sourcery-ai
Copy link

sourcery-ai bot commented Oct 18, 2025

Reviewer's Guide

Implements the myAtoi function by trimming leading spaces, determining sign, accumulating digits into a 64-bit accumulator with overflow/underflow checks, and returning a clamped int result.

Class diagram for the new Solution class implementing myAtoi

classDiagram
class Solution {
  +int myAtoi(string s)
}
Loading

Flow diagram for the myAtoi string to integer conversion process

flowchart TD
    A["Start"] --> B["Trim leading spaces"]
    B --> C["Check if string is empty after trimming"]
    C -->|Empty| D["Return 0"]
    C -->|Not empty| E["Check sign (+/-)"]
    E --> F["Iterate over digits"]
    F --> G["Accumulate number (ans = ans * 10 + digit)"]
    G --> H["Check for overflow/underflow"]
    H -->|Overflow/Underflow| I["Return INT_MAX/INT_MIN"]
    H -->|No overflow| J["Continue iteration"]
    J --> F
    F -->|No more digits| K["Return ans * sign as int"]
Loading

File-Level Changes

Change Details Files
Preprocess input and handle empty input
  • Skip leading spaces via while loop
  • Check if index reached string length and return 0
8. String to Integer (atoi).cpp
Determine numeric sign
  • Detect '-' to set sign = -1 and increment index
  • Detect '+' to leave sign positive and increment index
8. String to Integer (atoi).cpp
Accumulate digits and detect overflow/underflow
  • Loop while characters are digits and update ans = ans * 10 + digit
  • After each update, compare against INT_MAX/INT_MIN and return clamped value
8. String to Integer (atoi).cpp
Finalize and return result
  • Multiply accumulated value by sign
  • Cast result to int for return
8. String to Integer (atoi).cpp

Possibly linked issues

  • 322. Coin Change #8: The PR provides the C++ solution for LeetCode problem 8, String to Integer (atoi), as described in the issue.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for raising the PR, the owner will be review it soon' keep patience, keep contributing>>>!!! make sure you have star ⭐ the repo

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Change the signature to int myAtoi(const string& s) to avoid copying the input string on each call.
  • Instead of accumulating into a long long and checking for overflow afterward, pre-check ans > INT_MAX/10 or (ans == INT_MAX/10 && digit > INT_MAX%10) to handle overflow without needing a wider type.
  • Use more descriptive variable names (e.g. n or length instead of l) to improve code readability.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Change the signature to `int myAtoi(const string& s)` to avoid copying the input string on each call.
- Instead of accumulating into a `long long` and checking for overflow afterward, pre-check `ans > INT_MAX/10` or `(ans == INT_MAX/10 && digit > INT_MAX%10)` to handle overflow without needing a wider type.
- Use more descriptive variable names (e.g. `n` or `length` instead of `l`) to improve code readability.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@ayushHardeniya ayushHardeniya mentioned this pull request Oct 18, 2025
4 tasks
@SjxSubham SjxSubham linked an issue Oct 18, 2025 that may be closed by this pull request
4 tasks
@SjxSubham
Copy link
Owner

@ayushHardeniya
all looks good

Star the repo⭐ as well ...

@SjxSubham SjxSubham added the hacktoberest-accepted hacktoberfest-accepted label Oct 18, 2025
@SjxSubham SjxSubham merged commit 21e9c88 into SjxSubham:main Oct 18, 2025
2 checks passed
@ayushHardeniya ayushHardeniya deleted the add-solution-8-atoi branch October 18, 2025 16:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hacktoberest-accepted hacktoberfest-accepted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 : String to Integer (atoi)

2 participants