"Programming Thinking and Practice" 1041. Hexadecimal

"Programming Thinking and Practice" 1041. Hexadecimal

topic

insert image description here
insert image description here

train of thought

Since the first digits of two hexadecimal numbers will not meet, you can directly determine whether there is a hexadecimal number by finding the position where 0x appears:

1. Use the strstr function to find the position of the first 0x;

2. After finding the position of 0x, start traversing from 0x, and judge whether the next digit is between 0 to 9 or a to f, and if it is not, you need to terminate the traversal;

3. After terminating the traversal, judge whether there is a legal hexadecimal number, and output it directly;

4. Iterate for the next round of search (repeatedly search until 0x does not appear later);

5. You need to use a variable to access the total statistical hexadecimal number, but when it is 0, you need to output -1;

Points to note:

Hexadecimal numbers are in the range of unsigned int.

the code

#include<stdio.h>
#include<string.h>

int count=0; //记录合法数字个数 
void solve(char *temp)
{
    
    
    unsigned int num=0;
    int flag=0;   //判断是否有十六进制的数字 
    for(int i=0;i<strlen(temp);i++)
	{
    
    
		if(temp[i]>='0'&&temp[i]<='9')
		{
    
    
			num=num*16+temp[i]-'0';
			flag=1;
		}
		else if(temp[i]>='a'&&temp[i]<='f')
		{
    
    
			num=num*16+temp[i]+10-'a';
			flag=1;
		}
		else
		{
    
    
			break;   //非合法数字直接终止循环
		}
	}
	if(flag)  //有合法数字
	{
    
    
		count++;
		printf("%u ",num);
	}
	temp=strstr(temp+2,"0x")==NULL?NULL:strstr(temp+2,"0x")+2;   //下一轮寻找
    if(temp!=NULL)
    {
    
    
        solve(temp);  //迭代
    }
}
int main()
{
    
    
	char s[100001];
	scanf("%s",s);
    char* temp=strstr(s,"0x")==NULL?NULL:strstr(s,"0x")+2;  //存搜索0x得到的地址(+2表示从0x后开始)
   	solve(temp);
	if(count==0)
	{
    
    
		printf("-1\n");
	}
	return 0;
} 

Guess you like

Origin blog.csdn.net/boxueyuki/article/details/130484651