數據結構與算法分析c++:棧的應用(1)

十進制和其他進制轉換

我們知道十進制數轉換成其他進制數就是不斷地除以該進制數,每次的餘數倒序組合在一起就是轉換後的進制數的值,倒序組合正好利用棧LIFO的特性。下面是實現的代碼,比較簡單,不做解釋。

#include <iostream> 
#include <stack>
using namespace std;

void convert(stack<char> &S, __int64 number, int base) {
    static char digit[] =
        { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    while (number > 0) {  //餘數進棧
        S.push(digit[number % base]);
        number /= base;
    }
    while (!S.empty()) {  //倒序取出
        cout << S.top();
        S.pop();
    }
    cout << endl;
}

測試代碼如下,

int main(int argc, char* argv[])
{
    int num, base;
    stack<char> s;
    cout << "input number and base" << endl;
    cin >> num >> base;
    convert(s, num, base);
    system("pause");
    return 0;
}

輸出結果
輸出結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章