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.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
spoilers alert... click to show requirements for atoi.
Subscribe to see which companies asked this question.
1 class Solution { 2 public: 3 int myAtoi(string str) { 4 int len = str.length(); 5 if (!len) return 0; 6 int i = 0; 7 while (i < len && str[i] == ' ') i++; 8 if (i == len) return 0; // string contains only whitespace 9 int pos = 1; // indicates whether it is an positive integer 10 if (str[i] == '-') { 11 pos = 0; // s[i] is the first non-whitespace character 12 i++; 13 } 14 else if (str[i] == '+') i++; 15 int out = 0; 16 while (i < len) { 17 int temp = (int)(str[i] - '0'); 18 if (temp < 0 || temp > 9) return (pos ? out : -out); 19 else { 20 int temp2 = out * 10 + temp; 21 if (temp2 / 10 != out) return (pos ? INT_MAX : INT_MIN); // avoid overflow 22 else out = temp2; 23 } 24 i++; 25 } 26 return (pos ? out : -out); 27 } 28 };