leetcode atoi


雖然一開始就參照c++的atoi,但是還是沒考慮到超過最大最小範圍。


int atoi1(const char *str) {
	int i = 0;
	unsigned int res = 0;
	bool negf = false;
	while (str[i] == ' ')i++;
	if (str[i] == '-')
	{
		negf = true; i++;
	}
	else if (str[i] == '+') i++;

	int j = i;
	while (str[j])
	{
		if (!isdigit(str[j]))
		{
			break;
		}
		j++;
	}

	while (i < j)
	{
		if (res > 214748364 || (res == 214748364 && str[i] - '0' > 7))
		{
			return negf ? 0 - 2147483648 : 2147483647;
		}
		res *= 10;
		res += str[i++] - '0';
	}

	return negf ? 0 - res : res;
}


發佈了50 篇原創文章 · 獲贊 1 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章