十进制转十六进制
【AC代码】:更简单采用直接输出的方式。
#include <iostream> #include <algorithm> #include <cstdio> using namespace std; int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int n = 0, cnt = 0, i = 0; cin >> n; char Hex[20]; if (0 == n) cout << 0; while (n) { int temp = n%16; n = n/16; switch(temp) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: Hex[cnt++] = temp+'0'; break; case 10: case 11: case 12: case 13: case 14: case 15: Hex[cnt++] = temp-10+'A'; break; } } for (i = cnt-1; i >= 0; i--) cout << Hex[i]; }
十六进制转十进制
【AC代码】:更简单采用直接输出的方式。
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cmath> using namespace std; int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); char Hex[20]; gets(Hex); int i = 0, len = strlen(Hex); long long int sum = 0; for (i = len-1; i >= 0; i--) { if (Hex[i] >= '0' && Hex[i] <= '9') sum += (Hex[i]-'0') * pow(16, len-1-i); else sum += (Hex[i]-'A'+10) * pow(16, len-1-i); } cout << sum; }
十六进制转十进制
【AC代码】:因为题目范围限制,所以不能采用直接输出的方式。
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cmath> #include <iomanip> using namespace std; #define MAX 100000+10 int toNum(char c) { if (c >= 'A') return c - 'A'+10; else return c - '0'; } int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int t = 0; cin >> t; while (t--) { char Hex[MAX]; cin >> Hex; int i = 0, len = strlen(Hex); if (1 == len%3) { cout << oct << toNum(Hex[0]); i = 1; } else if (2 == len%3) { cout << oct << toNum(Hex[0])*16 + toNum(Hex[1]); i = 2; } for ( ; i < len; i+=3) { cout << setw(4) << setfill('0') << oct << toNum(Hex[i])*256 + toNum(Hex[i+1])*16 + toNum(Hex[i+2]); } cout << endl; } }
原文地址:http://blog.csdn.net/weijj6608/article/details/44246435