atoi函數的實現

請實現函數int atoi(const char *nptr))

函數說明: atoi會掃描參數nptr字符串,跳過前面的空格字符,遇到數字或正負符號開始做轉換,直至遇到非數字或字符串結束時('\0')結束轉換,並將結果返回。

不同人能夠寫出不同水平的代碼,是考查coding能力的經典問題。

函數實現:

int atoi(const char* nptr)
{
	int result = 0;
	if(nptr == NULL)
	{
		return result;
	}

	//while(nptr==" ")
	while(*nptr==' ')
	{
		nptr++; 
	}

	bool flag = false;
	if(*nptr=='-')
	{
		flag = true;
		nptr++;
	}
	else
	{
		if(*nptr=='+')
		{
			nptr++;
		}
	}
	
	while(nptr != '\0')
	{
		int temp = *nptr - '0';
		if(temp < 0 || temp > 9)
		{
			break;
		}
		else
		{
			result = result * 10 + temp;
		}
		nptr++;
	}
	if(flag)
	{
		result = 0 - result;
	}
	return result;
}

測試用例:

void main()
{
	int num0 = atoi("+123455");
	printf("num0=%d\n", num0);

	int num1 = atoi("-123455");
	printf("num1=%d\n", num1);

	int num2 = atoi("    123455z");
	printf("num2=%d\n", num2);

	int num3 = atoi("-123455.5");
	printf("num3=%d\n", num3);
}


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