进制转换

n进制转换为10进制

\(2 < n \le 10\)\(n=16\)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;

int main() {
    int d;
    char ch[101];
    cin >> ch >> d;
    int len = strlen(ch);
	
    // (101)2 = 1 * 2 ^ 2 + 0 * 2 ^ 1 + 1 * 2 ^ 0 = 5
    // (12)8 = 1 * 8 ^ 1 + 2 * 8 ^ 0 = 10
    // (2A)16 = 2 * 16 ^ 1 + 10 * 16 ^ 0 = 42
    int a = 0, b, cur = 0;
    for (int i = len; i > 0; i--) {
          switch (ch[cur]) {
          case 'A': 
                b = 10;
                break;
          case 'B':
                b = 11;
                break;
          case 'C':
                b = 12;
                break;
          case 'D':
                b = 13;
                break;
          case 'E':
                b = 14;
                break;
          case 'F':
                b = 15;
                break;
          default:
                b = ch[cur] - '0';
          }
		
          a += b * pow(d, i - 1);
          cur++;
    }
	
    cout << a << endl;
    return 0;
}
posted @ 2020-05-21 10:43  洛灵酱爱次糖  阅读(65)  评论(0编辑  收藏