现在的位置: 首页 > 综合 > 正文

[LeetCode] atoi

2017年12月23日 ⁄ 综合 ⁄ 共 1607字 ⁄ 字号 评论关闭

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.

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.

LeetCode上这个atoi的需求蛮奇怪的,比如11a这样居然算是正确的。

刚开始用的是char* p =str ,而不是p=0,结果编译报错,这种错误一下居然看不到,瞬间想到腾讯面试时的一个同样的问题当时也没想到,哎,功力不够啊!

class Solution {
public:
int atoi(const char *str) {
    // Start typing your C/C++ solution below
	// DO NOT write int main() function
	if ( !str ) return 0;
	long long ans=0;
	int p = 0;
	while(str[p]==' ')
		p++;
	bool neg=false;
	if ( str[p]=='+' )
		p++;
	else if ( str[p]=='-' )
		neg=true,p++;
	else if (!(str[p]<='9'&&str[p]>='0'))
		return 0;
		
	while(str[p]!='\0'&&str[p]<='9'&&str[p]>='0')
	{
		ans=ans*10+str[p]-'0';
		p++;
	}

	ans=neg?-ans:ans;
	if ( ans >INT_MAX ) 
		return INT_MAX;
	else if ( ans<INT_MIN)
		return INT_MIN;
	else
		return ans;
}
   
};

抱歉!评论已关闭.