PTA: convert a hexadecimal number (15 points) (C language)

Interface definition function:
int htoi (S char []);

S user function is passed the parameters, the function returns a string to be hexadecimal digits (including the prefix 0x or 0X) equivalent to integer values ​​after the conversion.

Note that the total string length does not exceed 8 bits (comprising the prefix 0x or 0X).

Sample testing procedures referees:
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int htoi (char s []);

int pow (int m, int k ); / implemented by the referee program returns to the k power m, the function can be directly used in the preparation, this function may not be used /

int main()
{
char s[10];
scanf("%s", s);
printf("%d\n", htoi(s));
}

/ * Please fill in the answer here * /

Sample input:
0x3f

Sample output:
63

int htoi(char s[])
{
    int i = 0;
    int sign = 0;
    int sum = 0;
    sign = (s[i] == '-') ? -1:1;
    if (s[i] == '-' || s[i] == '+')
        i++;
    if (s[i] == '0')
        i++;
    if (s[i] == 'x' || s[i] == 'X')
        i++;
    for (; s[i] != '\0'; i++)
    {
        if (s[i] >= '0' && s[i] <= '9')
            sum = sum*16 + s[i] - '0';
        else if (s[i] >= 'a' && s[i] <= 'z')
            sum = sum*16 + s[i] - 'a' + 10;
        else
            sum = sum*16 + s[i] - 'A' + 10;
    }
    return sum*sign;
}
Published 58 original articles · won praise 21 · views 607

Guess you like

Origin blog.csdn.net/qq_45624989/article/details/105399538