Search code examples
swiftalgorithmatoi

String to Integer (atoi) [Leetcode] gave wrong answer?


String to Integer (atoi)

This problem is implement atoi to convert a string to an integer.

When test input = " +0 123"

My code return = 123

But why expected answer = 0?

======================

And if test input = " +0123"

My code return = 123

Now expected answer = 123

So is that answer wrong?


Solution

  • I think this is expected result as it said

    Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

    Your first test case has a space in between two different digit groups, and atoi only consider the first group which is '0' and convert into integer