hdu2013進位制轉換解題報告---資料結構(棧)
阿新 • • 發佈:2018-12-20
進位制轉換
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 65581 Accepted Submission(s): 35574
Problem Description
輸入一個十進位制數N,將它轉換成R進位制數輸出。
Input
輸入資料包含多個測試例項,每個測試例項包含兩個整數N(32位整數)和R(2<=R<=16, R<>10)。
Output
為每個測試例項輸出轉換後的數,每個輸出佔一行。如果R大於10,則對應的數字規則參考16進位制(比如,10用A表示,等等)。
Sample Input
7 2 23 12 -4 3
Sample Output
111 1B -11
題意:將n化為m進位制。
Code:
1.stack
(進位制轉換輸出與資料結構中棧的後進先出原理一樣)
#include<iostream> #include<sstream> #include<cstdlib> #include<cmath> #include<cctype> #include<algorithm> #include<cstring> #include<cstdio> #include<map> #include<vector> #include<stack> #include<queue> #include<set> #include<list> #define mod 998244353 #define Max 0x3f3f3f3f #define Min 0xc0c0c0c0 #define mst(a) memset(a,0,sizeof(a)) #define f(i,a,b) for(int i=a;i<b;i++) using namespace std; typedef long long ll; const int maxn = 1e6 + 5; int main(){ //ios::sync_with_stdio(false); int n, m; while(scanf("%d%d", &n, &m) != EOF){ stack<char>ss; if(n == 0){ printf("0\n"); continue; } if(n < 0){ n = -n; printf("-"); } while(n){ ss.push(n % m >= 10?(n % m - 10 + 'A'):(n % m + '0')); n /= m; } while(!ss.empty()){ printf("%c", ss.top()); ss.pop(); } printf("\n"); } return 0; }
2.陣列逆序輸出實現
#include<iostream> #include<sstream> #include<cstdlib> #include<cmath> #include<cctype> #include<algorithm> #include<cstring> #include<cstdio> #include<map> #include<vector> #include<stack> #include<queue> #include<set> #include<list> #define mod 998244353 #define Max 0x3f3f3f3f #define Min 0xc0c0c0c0 #define mst(a) memset(a,0,sizeof(a)) #define f(i,a,b) for(int i=a;i<b;i++) using namespace std; typedef long long ll; const int maxn = 1e6 + 5; int main(){ //ios::sync_with_stdio(false); int n, m; while(scanf("%d%d", &n, &m) != EOF){ if(n == 0){ printf("0\n"); continue; } char str[1005]; int len = 0; bool flag = false; if(n < 0){ n = -n; flag = true; } while(n){ str[len++] = n % m >= 10?(n % m - 10 + 'A'):(n % m + '0'); n /= m; } //int index = 0; while(!str[len - 1] && len > 0) len--; if(flag) printf("-"); for(int i = len - 1; i >= 0; i--){ printf("%c", str[i]); } printf("\n"); } return 0; }