Write the function htoi(s), which converts a string of hexadecimal digits(including an optional 0x or 0X)into its equialent integer value. The allowable digits are 0 through 9,a through f,and A through F. We make sure the 'int' type is enough.
编写函数htoi(s),它将十六进制数字字符串(包括可选的0x或0x)转换为其等位整数值(十进制)。允许的数字是0到9、a到f和a到f。我们确保“int”类型足够。
函数接口定义:
int htoi(char s[]);
裁判测试程序样例:
#include <stdio.h>
#define YES 1
#define NO 0
/* htoi:convert hexadecimal string s to integer */
int htoi(char s[]);
int main()
{
// freopen("2.in", "r", stdin);
// freopen("2.out", "w", stdout);
char A[12];
while(scanf("%s", A) != EOF) {
int v = htoi(A);
printf("%d\n", v);
}
return 0;
}
/* Your code will be copied here.*/
输入样例:
0xaB23
结尾无空行
输出样例:
43811
?我是从前往后来的,方法不是那么‘聪明’。
#include<math.h>
int htoi(char s[]){
int i,n,sum=0,j;
for(j=0;s[j]!='\0';j++);
j=j-2;
for(i=2;j>=0;i++,j--){//0x33
if(s[i]=='a'||s[i]=='A')
n=10;
else if(s[i]=='b'||s[i]=='B')
n=11;
else if(s[i]=='c'||s[i]=='C')
n=12;
else if(s[i]=='d'||s[i]=='D')
n=13;
else if(s[i]=='e'||s[i]=='E')
n=14;
else if(s[i]=='f'||s[i]=='F')
n=15;
else if(s[i]>='0'&&s[i]<='9')
n=s[i]-'0';
sum+=n*pow(16,j-1);
}
return sum;
}
|