首页 > 其他 > 详细

String to Integer (atoi)

时间:2015-03-27 10:59:54      阅读:111      评论:0      收藏:0      [点我收藏+]

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.

 

int atoi(string str) {
	int result =0;
	bool beone = true;
	int flag =1; 
	int k =0;
	while (k<str.size()&&str[k]==' ')
		k++;
	for (int i = k;i!=str.size();++i){
		if (str[i] == '-'||str[i] == '+'){
			if (beone){
				flag = str[i] == '-'? -1:1;
				beone = false;
				continue;
			}	
			else
				return 0;	
		}
		else if (str[i]>='0'&&str[i]<='9')
		{
			if(result > INT_MAX/10||(result == INT_MAX/10&&str[i]-'0'>7))//out of range  
				return flag < 0 ? INT_MIN : INT_MAX;
			result = 10*result+str[i]-'0';
			
		}	
		else
			break;		
	}
	return flag*result;
}


 

String to Integer (atoi)

原文:http://blog.csdn.net/li_chihang/article/details/44671863

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!