进制转换问题

十进制转N进制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <cstdio>
using namespace std;
string (int x, int n){
const string a = "0123456789ABCDEF";
string s = "";
if(x == 0)
return "0";
while(x > 0){
s = a[x%n] + s;
x /= n;
}
return s;
}
int main(){
int x, n;
cin >> x >> n;
cout << fun(x, n) << endl;
system("pause");
return 0;
}

N进制转十进制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <string>
using namespace std;
int (int n, string s){
int i, t=0;
for(i=0;i<=s.size();i++){
if(s[i]>='0' && s[i]<'9'){
t = t*n+s[i]-48;
}
if(s[i]>='A' && s[i]<='F'){
t = t*n+s[i]-55;
}
if(s[i]>='a' && s[i]<='f'){
t = t*n+s[i]-87;
}
}
return t;
}
int main(){
int n;
string str;
cin >> n >> str;
cout << fun(n, str) << endl;
system("pause");
return 0;
}