String to Integer (atoi)
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.
边界条件太多,题目也没i说清楚,都是根据测试数据修改程序……也算过了
Runtime: 15 ms
#include <stdio.h> #include <stdlib.h> #include <string> using namespace std; class Solution { public: int myAtoi(string str) { double num = 0; bool isPositive = true; if (str=="") return 0; int i = 0; while (str[i] == ' ') i++; if (str[i] == '-'){ isPositive = false; i++; if (str[i] == '+'||str[i]=='-'){ return 0; } } if (str[i] == '+'){ i++; if (str[i] == '+' || str[i] == '-'){ return 0; } } while (i <str.length()&&str[i]>='0'&&str[i]<='9'){ num = num * 10 + (str[i]-'0'); i++; } if (isPositive == false){ num = num*-1; } if (num > INT_MAX) return INT_MAX; else if (num < INT_MIN) return INT_MIN; else return num; } }; int main(){ Solution solution; printf("%d", solution.myAtoi(" -123")); system("pause"); }