1. 程式人生 > >HDU 2031 進制轉換

HDU 2031 進制轉換

align 包含 blog else close arc math ott algo

進制轉換

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 58687 Accepted Submission(s): 31957


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

Author lcy

Source C語言程序設計練習(五)

技術分享圖片
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<set>
#include<map>
#include<sstream>
#include
<queue> #include<stack> #include<cmath> #include<list> #include<vector> #include<string> using namespace std; #define long long ll const double PI = acos(-1.0); const double eps = 1e-6; const int inf = 0x3f3f3f3f; const int N = 500005; int n, m, tot; int a[N]; stack
<char> s; int main() { while(cin >> n >> m ) { if(n<0) cout<<"-"; int tmp; while(n) { tmp = n%m; tmp = tmp>0?tmp:-tmp; if(tmp<10) s.push(tmp +0); else s.push(tmp - 10 + A); n /= m; } while(!s.empty()) { cout<<s.top(); s.pop(); } cout<<endl; } }
除基取余+satck逆序輸出

技術分享圖片
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<set>
#include<map>
#include<sstream>
#include<queue>
#include<stack>
#include<cmath>
#include<list>
#include<vector>
#include<string>
using namespace std;
#define long long ll
const double PI = acos(-1.0);
const double eps = 1e-6;
const int inf = 0x3f3f3f3f;
const int N = 500005;
int n, m, tot;
int a[N];
stack<char> s;
void print(int a)
{
    if(a<10) cout<<a;
    else cout<<(char)(a-10+A);
}
int main()
{
    while(cin >> n >> m )
    {
        if(n<0)
            cout<<"-",n=-n;
        int tmp, k = 0;
        while(n)
        {
            a[++k] = n % m;
            n /= m;
        }
        for(int i=k; i>=1; i--)
        {
            print(a[i]);
        }
        cout<<endl;
    }
}
View Code

HDU 2031 進制轉換