机试笔记3--进制转换
1.求反序数
#include <iostream> using namespace std; int main() { int n; cin >> n; int ans = 0; while(n>0){ ans = ans*10+n%10; n/=10; } return 0; }
2.十进制转x进制
#include <iostream> #include <vector> using namespace std; /*通用版*/ int main() { int num,x; cin >> num>>x; vector<char> bin; while(num>0){ int w = num%x; if(w<10) bin.push_back(w+'0'); else bin.push_back(w-10+'A'); num/=x; } for(int i=bin.size()-1;i>=0;i--){ cout << bin[i]; } cout << endl; return 0; }
3.X进制转10进制
#include <iostream> #include <vector> #include <math.h> using namespace std; int main() { string n; int x;//输入数据和该数的进制 cin >> n >> x; int len = n.size(); int sum_m = 0; int j=0; for(int i=len-1;i>=0;i--){ int p = pow(x,j); if('A'<=n[i]&&n[i]<='Z'){ sum_m+=(n[i]-'A'+10)*p; }else{ sum_m+=(n[i]-'0')*p; } j++; } cout << sum_m<<endl; return 0; }
4.M进制转N进制
先转成10进制,再转成N进制
#include <iostream> #include <vector> #include <math.h> using namespace std; //M进制转10进制 int mToten(string n,int x) { int len = n.size(); int sum_m = 0; int j=0; for(int i=len-1;i>=0;i--){ int p = pow(x,j); if('A'<=n[i]&&n[i]<='Z'){ sum_m+=(n[i]-'A'+10)*p; }else{ sum_m+=(n[i]-'0')*p; } j++; } return sum_m; } //10进制转N进制 string tenTon(int n,int x) { string a; string ans; while(n>0){ int w = n%x; if(w>9){ a+=(w-10)+'a'; } else a+=(w+'0'); n/=x; } for(int i=(a.size()-1);i>=0;i--) ans+=a[i]; return ans; } int main() { int M,N; string x; cin >> M >> N; cin >> x; int num = mToten(x,M); string str = tenTon(num,N); cout << str; return 0; }