面试题整理 1:将一个字符串转换为整数

题目:输入一个表示整数的字符串,把该字符串转换成整数并输出。

分析:这道题尽管不是很难,学过C/C++语言一般都能实现基本功能,但不同程序员就这道题写出的代码有很大区别,可以说这道题能够很好地反应出程序员的思维和编程习惯,因此已经被包括微软在内的多家公司用作面试题。


C自带 atoi的要求:

Convert string to integer
Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.

The function first discards as many whitespace characters (as in isspace) 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 base-10 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 and zero is returned.

1、注意容易出错的地方:

(1)空指针的处理;一定注意代码的鲁棒性!

(2)忽略前面的空格,空格有多种表示方法;

(3)‘+'或者'-'的处理。因此需要把这个字符串的第一个字符做特殊处理。如果第一个字符是'+'号,则不需要做任何操作;如果第一个字符是'-'号,则表明这个整数是个负数,在最后的时候我们要把得到的数值变成负数。

(4)溢出问题,处理方式;int的范围为  - 0x 7FFF(FFFF) ~ 0x 7FFF(FFFF)。因为int 占4个字节,字节位数和开发环境有关系,有16位的也有32位的,现在大多数计算机是32位的,即范围为-0x7FFF~0x7FFF或者-0x7FFFFFFF~-0x7FFFFFFF。

(5)当字符串不能转化为整数的错误处理;采用数字后面有非数字字符时进行忽略的方式。

2、声明

首先我们考虑如何声明这个函数。由于是把字符串转换成整数,很自然我们想到:
int StrToInt(const char* str);

这样声明看起来没有问题。但当输入的字符串是一个空指针或者含有非法的字符时,应该返回什么值呢?0怎么样?那怎么区分非法输入和字符串本身就是”0”这两种情况呢?

接下来我们考虑另外一种思路。我们可以返回一个布尔值来指示输入是否有效,而把转换后的整数放到参数列表中以引用或者指针的形式传入。于是我们就可以声明如下:
bool StrToInt(const char *str,int& num);
这种思路解决了前面的问题。但是这个函数的用户使用这个函数的时候会觉得不是很方便,因为他不能直接把得到的整数赋值给其他整形,显得不够直观。
前面的第一种声明就很直观。如何在保证直观的前提下当碰到非法输入的时候通知用户呢?一种解决方案就是定义一个全局变量,每当碰到非法输入的时候,就标记该全局变量。用户在调用这个函数之后,就可以检验该全局变量来判断转换是不是成功。

不过在面试时,我们可以选用任意一种声明方式进行实现。但当面试官问我们选择的理由时,我们要对两者的优缺点进行评价。

第二种声明方式对用户而言非常直观,但使用了全局变量,不够优雅;而第一种思路是用返回值来表明输入是否合法,在很多API中都用这种方法,但该方法声明的函数使用起来不够直观。


3、实现

在c的atoi函数中对于不含数字或者不能转换的字符串输出0,这里同样采用此种方法。

bool isspace(char x)
{
	if(x==' '||x=='\t'||x=='\n'||x=='\f'||x=='\b'||x=='\r')
		return true;
	else  
		return false;
}

int atoi(char *nptr)
{
	if( !nptr ){ //null
	   return 0;
	}
	int result = 0;         /* current result */
	bool isNeg = false;           /* if '-', then negative, otherwise positive */
	
	/* skip whitespace */
	while ( isspace(*nptr) )
		++nptr;

	if ( *nptr == '-'){
		isNeg = true;
		nptr++;  /* skip sign */
	}else if ( *nptr == '+'){
		isNeg = false;
		nptr++;  /* skip sign */
	}

	while ( *nptr != '\0') { //not end 
		if( *nptr < '0' || *nptr > '9' ){  //non-number
			break;
		}
		result = 10 * result + (*nptr - '0');     /* accumulate digit */
		if(result > 0X7FFFFFFF) /* over flow 32*/
		{
			cout << "over flow" << endl;
			result = 0;
			break;
		}
		nptr++;    /* get next  */
	}

	if (isNeg)
		result = - result;

	return result;
} 




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值