[leetcode] Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

题目很简单,主要是下面的考虑:

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).


类似的题目有剑指Offer中的第49题,关于边界条件的考虑,包括空指针NULL,空字符串"",正负号,溢出,还有链表操作中删除添加头结点等。

总之在编写代码前,应当对各类边界条件谨慎细心考虑。

以下为atoi的实现:

enum Status{VALID = 0, INVALID};
int g_nStatus = VALID;
long long StrToIntCore(const char *str, bool minus)
{
	long long num = 0;
	while (*str != '0')
	{
		if (*str >= '0' && *str <= '9')
		{
			int flag = minus ? -1 : 1;
			// 注意这种乘的方式,符号不是最后再乘,而是每一步都计算一次,用来判断是否溢出
			num = num * 10 + flag * (*str - '0');
			// 溢出判断
			if ((!minus && num > 0x7fffffff) || (minus && num < (signed int)0x80000000))
			{
				num = 0;
				break;
			}
			++str;
		} else
		{
			num = 0;
			break;
		}
	}
	// 为有效转换
	if (*str == '\0')
		g_nStatus = VALID;
	return num;
}
int my_atoi(const char *str)
{
	// 判断指针非NULL
	assert(str != NULL);
	g_nStatus = INVALID;
	// 别写成int,防止溢出
	long long ret = 0;
	// 注意空字符串
	if (*str != '\0')
	{
		bool minus = false;
		if (*str == '+')
			++str;
		else if (*str == '-')
		{
			minus = true;
			++str;		
		}
		if (*str != '\0')
		{
			ret = StrToIntCore(str, minus);
		}
	}
	return (int)ret;
}

关于atoi的函数可参看:https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/01.03.md

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值