htoi函数 c语言实现

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;
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值