[C++]進位制轉換(2~16)
阿新 • • 發佈:2018-11-25
Tips:此Code引用了STL庫,已引用函式註釋如下:
Origin Url:http://www.cplusplus.com/reference/algorithm/reverse/
template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last);
反向範圍
反轉範圍中元素的順序
[first,last)
。
函式呼叫iter_swap將元素交換到新位置。
此函式模板的行為等效於:template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last) { while ((first != last) && (first != --last)) { std::iter_swap (first, last); ++first; }; };
引數 first, last
雙向迭代器到要反轉的序列的初始和最終位置。使用的範圍是
[first,last)
,它包含所有的元件第一和最後一個,包括由指向的元件第一但不被指向的元素最後。
BidirectionalIterator 應指向哪種型別 交換 是否正確定義。
例子
// reverse algorithm example #include <iostream> // std::cout #include <algorithm> // std::reverse #include <vector> // std::vector int main () { std::vector<int> myvector; // set some values: for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9 std::reverse(myvector.begin(),myvector.end()); // 9 8 7 6 5 4 3 2 1 // print out content: std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0; }
輸出:myvector contains: 9 8 7 6 5 4 3 2 1
程式程式碼:
#include <algorithm> #include <iostream> #include <string> #include <cstdio> #include <cctype> using namespace std; const char Form[] = {"0123456789ABCDEF"}; inline int data(const char ch) { for (int i = 0; i < 16; ++i) if (ch == Form[i]) return i; return -1; }; inline void a_to_decimal(const int a, string &str) { const int len = str.length(); int answer = 0; int weight = 1; for (int i = len - 1; i >= 0; --i) { int temp = data(str[i]); answer += temp * weight; weight *= a; }; string cache = ""; while (answer > 0) { cache.push_back(answer % 10 + '0'); answer /= 10; }; reverse(cache.begin(), cache.end()); str = cache; }; inline void decimal_to_b(const int b, string &str) { const int len = str.length(); int answer = 0; int weight = 1; for (int i = len - 1; i >= 0; --i) { int temp = data(str[i]); answer += temp * weight; weight *= 10; }; string cache = ""; while (answer > 0) { cache.push_back(Form[answer % b]); answer /= b; }; reverse(cache.begin(), cache.end()); str = cache; }; inline void conversion(const int a, string &str, const int b) { a_to_decimal(a, str); decimal_to_b(b, str); if (str.empty()) str.push_back('0'); }; int main(int argc, char *argv[]) { int a, b; string str; cin >> a >> str >> b; for (int i = 0; i < str.size(); ++i) str[i] = toupper(str[i]); conversion(a, str, b); cout << str << endl; return 0; };