Why 123e4 or 123E4 not supported in standard atoi()? Really wired.


  • 0
    J

    standard atoi():
    123e4 or 123E4 ==> output: 123
    But I think it should return 1230000. Any comments?


  • 2
    M

    atoi, as defined by both this problem and the c++ manual, discards all non-numeric portions of the string, ignoring everything that comes after it. This includes the exponential. While there could be several other reasons for this, this is the clearest I thought of.

    123e4 translates to 1230000, fine. That works great and can be stored easily in an int. However, 123e8 translates to 12,300,000,000, which overflows an int. You could have e defined for the small range of values up through 10 at the most, but it is more consistent to just truncate it. Otherwise e11 and up would all have undefined behavior (translate to 2147483647, in this problem).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.