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.
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.
The string can contain 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 performed.
If no valid conversion could be performed, 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.
题目的意思就是实现string里的函数atoi(),它的要求如上所述:
1. 丢弃字符串前面的所有空白字符串,直至遇到非空的数字或者"+"和“-”,开始转化。
2. 数字结尾可以包含无意义的字符串,忽略就好
3.第一个非空的字符没有意义,就不发生转化
4.不发生转化时,返回0.对于超过INT的取值范围的边界情况,要分别返回INT_MIN和INT_MAX
不要忘记C++的一个重要字符函数库cctype
class Solution {
public:
int myAtoi(string str) {
int i,n=str.size();
int co=1;//int值得系数,初始时值1,遇到"-"时,设为-1
long long sum=0;//设为long long的字符型,因为转化超过INT_MIN~INT_MAX的范围,只是int型会溢出
i=0;
//第一个循环用来跳过空白字符,直至遇到第一个非空字符
while(i
INT_MAX))//处理边界情况
return INT_MAX;
else if((co==-1)&&(sum*10+(str[i]-'0'))*(-1)