欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

oral_quiz->#Str2Int#

程序员文章站 2024-02-28 11:32:46
...
#include <stdio.h>
#include <string>

enum Status { kValid = 0, kInvalid };
int g_nStatus = kValid;

long long Str2IntCore(const char* digit, bool minus);
int Str2Int(const char* str) {
	g_nStatus = kInvalid;
	long long num = 0;

	if(str != NULL && *str != '\0') {
		bool minus = false;
		if(*str == '+')
			str++;
		else if(*str == '-') {
			minus = true;
			str++;
		}

		if(*str != '\0')
			num = Str2IntCore(str, minus);
	}

	return (int)num;
}

long long Str2IntCore(const char* digit, bool minus) {
	long long num = 0;

	while(*digit != '\0') {
		if(*digit >= '0' && *digit <= '9') {
			int flag = minus ? -1 : 1;
			num = num*10 + flag*(*digit - '0');

			if((!minus && num > 0x7FFFFFFF) || (minus && num < (signed int)0x80000000)) {
				num = 0;
				break;
			}

			digit++;
		}
		else {
			num = 0;
			break;
		}
	}

	if(*digit == '\0')
		g_nStatus = kValid;

	return num;
}

void Test(const char* testName, const char* str, int expected) {
	if(testName != NULL)
		printf("%s begins: ", testName);

	if(expected == Str2Int(str))
		printf("passed.\n");
	else
		printf("failed.\n");

	printf("g_nStatus: %d\n", g_nStatus);
}

//positive
void Test1() {
	char* str = "7865";
	Test("Test1", str, 7865);
}

//negative
void Test2() {
	char* str = "-7865";
	Test("Test2", str, -7865);
}

//NULL
void Test3() {
	Test("Test3", NULL, 0);
}

//""
void Test4() {
	char* str = "";
	Test("Test4", str, 0);
}

//Invalid
void Test5() {
	char* str = "+8j7";
	Test("Test5", str, 0);
}

//beyond
void Test6() {
	char* str = "5463728392";
	Test("Test6", str, 0);
}

int main(int argc, char* argv[]) {
	Test1();
	Test2();
	Test3();
	Test4();
	Test5();
	Test6();

	return 0;
}



转载于:https://my.oschina.net/ITHaozi/blog/283383