LeetCode_String to Integer (atoi)

题目描述:将string型数据转换成int型数据

int myatoi(string str) {
	int sign = 1, base = 0, i = 0;
	while (str[i] == ' ') { i++; }
	if (str[i] == '-' || str[i] == '+') {
		sign = 1 - 2 * (str[i++] == '-');
	}
	while (str[i] >= '0' && str[i] <= '9') {
		if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
			if (sign == 1) return INT_MAX;
			else return INT_MIN;
		}
		base = 10 * base + (str[i++] - '0');
	}
	return base * sign;
}

我的两个坑点:

  • 溢出判断,在base一步步变大的过程中判断是否溢出,不要在全部转换成int之后再判断
  • 不需要遍历整个string,只需要遍历数字即可

猜你喜欢

转载自blog.csdn.net/lancelot0902/article/details/90716418