Implement atoi to convert a string to an integer.
Hint: carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: it is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Spoilers alert... click to show requirements for atoi.
Requirements for atoi:
The function first discards as your 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 your numerical digits as possible, and interprets them as a numerical value.
The string can contain in additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in STR is not a valid integral number, or if no such sequence exists because either STR is empty or it contains only whitespace characters, no conversion is saved med.
If no valid conversion cocould be specified med, a zero value is returned. If the correct value is out of the range of representable values, int_max (2147483647) or int_min (-2147483648) is returned.
My code...
// Stringtointeger. cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <string. h> # include <limits. h> # include <iostream> using namespace STD; Class solution {public: int atoi (const char * Str) {int Len = strlen (STR); If (LEN = 0) return 0; int Index = 0; int flag = 1; while (index <Len) {If (STR [Index]> = '0' & STR [Index] <= '9') {break ;} else if (STR [Index] = '+') {flag = 1; index ++; break;} else if (STR [Index] = '-') {flag =-1; index ++; break;} else if (STR [Index] = '') {index ++;} else {break ;}} // cout <index <"PP" <Endl; If (Index = Len) return 0; int sum = 0; while (index <Len) {If (STR [Index]> = '0' & STR [Index] <= '9') {If (flag = 1) {If (sum> int_max/10) {return int_max;} If (sum * 10> int_max-(STR [Index]-'0 '))) {return int_max ;}} else {If (flag * sum <int_min/10) {return int_min ;} if (flag * sum * 10 <(int_min-flag * (STR [Index]-'0') {return int_min ;}} sum = sum * 10 + (STR [Index]-'0'); // cout <sum <Endl;} elsebreak; index ++ ;} return sum * flag ;}}; int _ tmain (INT argc, _ tchar * argv []) {solution SS; char * s = "-2147483649"; cout <ss. atoi (s) <Endl; System ("pause"); Return 0 ;}
The difficulty is to determine the overflow part, and it feels a bit scum to implement it...
Or use the long type directly. It is relatively simple. You can directly determine the size of int_max and int_min.
[Leetcode] string to INTEGER (atoi)