Lab 7-3-6 Converting Strings to Decimal Integers (15 points)

Lab 7-3-6 Converting Strings to Decimal Integers (15 points)
Enter a string ending with #, this question requires filtering out all non-hexadecimal characters (case-insensitive), forming a new string representing hexadecimal numbers, and then converting it to decimal numbers output. If the character "-" is present before the first hexadecimal character, the number is negative.

Input format:
Input gives a non-empty string terminated by # on one line.

output format
Output the converted decimal number in one line. The title guarantees that the output is in the long range.

Input sample:
+-P-xf4+-1!#

Sample output:
-3905

#include<stdio.h>
#define N 20
//Idea: Set two flag bits to record the position of the first negative sign and the position of the first hexadecimal (used to judge positive and negative)
// Compare the size of the two positions and determine whether the result is negative.
// Convert hexadecimal to decimal, set a variable temp=1, then update temp *= 16 to get the corresponding result.
int main(void)
{
	int i, len=0, index1=-1, index2=-1, cnt = 0, temp=1, sum=0;
	char str1[N]; //input string
	char str2[N]; //hex string
	int str3[N]; // string in numeric form
	char ch;

	ch = getchar(); // read string
	for (i = 0; ch != '#'; i++)
	{
		str1[i] = ch;
		len ++;
		ch = getchar();
	}

	for (i = 0; i < len; i++) //find the position of the first symbol
	{
		if (str1[i] == '-')
		{
			index1 = i;
			break;
		}
	}

	for (i = 0; i < len; i++) //find the position of the first hex
	{
		if ((str1[i] >= 'A' && str1[i] <= 'F') || (str1[i] >= 'a' && str1[i] <= 'f') || (str1[i] >= '0' && str1[i] <= '9'))
		{
			index2 = i;
			break;
		}
	}

	for (i = 0; i < len; i++) // extract all hexadecimal numbers or letters
	{
		if ((str1[i] >= 'A' && str1[i] <= 'F') || (str1[i] >= 'a' && str1[i] <= 'f') || (str1[i] >= '0' && str1[i] <= '9'))
		{
			str2[cnt] = str1[i];
			cnt++;
		}
	}

	for (i = 0; i < cnt; i++) //Process hexadecimal letters, each character becomes a number
	{
		if ((str2[i] >= 'A' && str2[i] <= 'F'))
		{
			str3[i] = str2[i] - 'A' + 10;
		}
		if ((str2[i] >= 'a' && str2[i] <= 'f'))
		{
			str3[i] = str2[i] - 'a' + 10;
		}
		if ((str2[i] >= '0' && str2[i] <= '9'))
		{
			str3[i] = str2[i] - '0';
		}
	}

	for (i = cnt-1; i >= 0; i--) //hex to decimal
	{
		sum += str3[i] * temp; //set temporary variable
		temp *= 16;
	}

	if (index1>-1) //In the case of guaranteeing a negative sign, output the result
	{
		if (index1 > index2)
		{
			printf("%d\n", sum);
		}
		else if (index1 < index2)
		{
			printf("-%d\n", sum);
		}
	}
	else
	{
		printf("%d\n", sum);
	}
	return 0;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326814009&siteId=291194637