题解 | #HJ5 进制转换#
进制转换
http://www.nowcoder.com/practice/8f3df50d2b9043208c5eed283d1d4da6
三种方法
- 以十六进制数读入,以十进制数输出
- 调用
strtol
转换 - 自己手动算
#include <stdio.h>
#include <math.h>
#define FLAG 1
#if FLAG
int func1(char hexStr[]) {
int decimal = 0;
for(int i = strlen(hexStr)-1; i >=2; i--) {
int value;
if ('A' <= hexStr[i] && hexStr[i] <= 'F') {
value = hexStr[i] - 'A' + 10;
} else if ('a' <= hexStr[i] && hexStr[i] <= 'z') {
value = hexStr[i] - 'a' + 10;
} else if ('0' <= hexStr[i] && hexStr[i] <= '9') {
value = hexStr[i] - '0';
}
decimal += value * (int)pow(16, strlen(hexStr)-i-1);
}
return decimal;
}
int func2(char hexStr[]) {
char* ptr;
int decimal = strtol(hexStr, &ptr, 16);
return decimal;
}
#endif
int main() {
int decimal;
#if FLAG
char hexStr[8];
while (scanf("%s", hexStr) != EOF) { // 注意 while 处理多个 case
// 64 位输出请用 printf("%lld")
decimal = func2(hexStr);
printf("%d\n", decimal);
}
#else
while(scanf("%x", &decimal) != EOF)
printf("%d\n", decimal);
#endif
return 0;
}