Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[string_integer_interconversion problem] The solution in the book does not pass all test cases #188

Open
nv-quan opened this issue Aug 16, 2020 · 1 comment

Comments

@nv-quan
Copy link

nv-quan commented Aug 16, 2020

The solution in the book does not check for the first '+' character, which appears in one of test cases (2/15002). And also I think the description in the book is not clear enough about all the ill-form input like "+4176473".

@MichaelBagnasco
Copy link

I ran into the same issue. Simply adding s[0] == '+' to the accumulate begin check fixes it.

Old (solution from the book)

int StringToInt(const string& s) {
  return (s[0] == '-' ? -1 : 1) * std::accumulate(std::begin(s) + (s[0] == '-'), std::end(s), 0, [](int running_sum, char c) {
    return running_sum * 10 + c - '0';
  });
}

New

int StringToInt(const string& s) {
  return (s[0] == '-' ? -1 : 1) * std::accumulate(std::begin(s) + (s[0] == '-' || s[0] == '+'), std::end(s), 0, [](int running_sum, char c) {
    return running_sum * 10 + c - '0';
  });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants