CVTE的笔试题目

CVTE的笔试题目:
要求在数组 A [ 1 00 ]中按输入的范围表达式求和”表示从 m 到末尾 : m ·函数实现累加功能支梯浓口卞 2 种字符侧覃表示符,
" n : m " ”表示从n到 m , " :m ”表示从 o 到 m ,
"m:"表示从m-99;
char range1[17] = “3:7,9,45,2,77:78”;
即 93 + 4 + 5 +6 + 7 + 9 + 45 + 2 + 77 + 78+79)
char range2[10] = “:3,50,97:”;
1 + 2 + 3 + 50 + 97 + 98 + 99 )
写出求和函数:
int Sum ( char * ange )

int Sum(char *range)
{
	int sum=0;
	int first1=0, first2=0;
	int last1=0, last2=0;
	int A[100] = { 0 };
	int index=0;
	int i=0;
	int j=0;
	if (range == NULL)
		return 0;
	int len = strlen(range);
	int all_len=0;
	char *temp = range + len-1;
	int state=0;
	while (len > all_len)
	{
		switch (state)
		{
		case 0:
			if (*temp == ':') //最后一个
			{
			//	printf("all_len=%d\n", all_len);
				state = 1;
				i = 0;
				temp--;
			}
			else if (*temp == ',')
			{
				//printf("1\n");
				state = 2;
				temp--;
				i = 0;
			}
			else {
				last2 += ((*temp) - 48)*pow(10, i);
				temp--;
			//	printf("last2=%d\n", last2);
				i++;
			}
			all_len++;
			break;
		case 1:
			if (*temp == ',')
			{
				state = 2;
				//printf("all_len=%d\n", all_len);
				temp--;
				i = 0;
			}
			else {
				last1 += (*temp - 48)*pow(10, i);
			//	printf("last1=%d\n", last1);
				temp--;
				i++;
			}
			all_len++;
			break;
		case 2:
			if (*temp == ':')
			{
			//	printf("all_len=%d\n", all_len);
				state = 3;
				temp--;
				i = 0;
			}
			else if (*temp == ',')
			{
				index++;
				temp--;
				i = 0;
			}
			else
			{
			
			A[index] += (*temp - 48)*pow(10, i);
			temp--;
			i++;
				}
				all_len++;
				break;
			case 3:
				if (len == i)
					break;
				else {
					first1 += (*temp - 48)*pow(10, i);
				//	printf("first1=%d\n", first1);
					temp--;
					i++;
				}
				all_len++;
			default:break;
			}
	}
	//========FISRT========
	first2 = A[index];
		if (first1 == 0)
		{
			for (j = 0; j <= first2; j++)
			{
				sum += j;
			}
		}
		else {
			for (j = first1; j <= first2; j++)
			{
				sum += j;
			}
		}
		//===lastt==
		if (last2 == 0)
		{
			for (j = last1; j <= 99; j++)
			{
				sum += j;
			}
		}
		else {
			for (j = last1; j <= last2; j++)
			{
				sum += j;
			}
		}

		for (j = 0; j < index; j++)
		{
			sum += A[j];
		}
	return sum;

}

你可能感兴趣的:(C/C++)