题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { //最大值为2^31-1,即代表了不会超过int类型的数据 //保险起见采用long进行数据的存储 //对于32位的数据,采用10位的数组存储字符即可,其中数字不变 //可能出现字符a-z和A-Z,要分别处理 char hex[11]={}; while(gets(hex)){ long tmp = 0; for(int i=2;i<strlen(hex);i++){ if(hex[i]>='0'&&hex[i]<='9'){ tmp = tmp*16+(hex[i]-'0'); } else if(hex[i]>='a'&&hex[i]<='f'){ tmp = tmp*16+(hex[i]-'a'+10); } else{ tmp = tmp*16+(hex[i]-'A'+10); } } printf("%d\n",tmp); } return 0; }
由于不确定后台的测试用例是否区分大小写,因此在这里通通考虑上;
根据题目给定的格式,暂且假设所有的数据都是0x开头;
根据给出数据的范围,接收的数组开辟不需要很大;
根据进制转换的计算公式,可以使用数学中的逐层计算减少总体的运算量。