題目: UVa - 389 - Basically Speaking
題目說明
給一個字串表示數值,及 n、m,表示該值是 n 進位,要求轉換為 m 進位。
除此之外,有三個要求:
- 轉換後不可超過 7 位數,若超過則輸出 "ERROR"。
- 字串只會出現 A ~ F 及 0 ~ 9。
- n、m 的範圍為 2 ~ 16。
且輸出時需靠右對齊。
Input: 每行有三個變數,分別為該字串、n、m
Output: 輸出轉換後的數值。
解題思路
根據題目要求做轉換,先轉換為十進位再轉換成題目要求的進位數,需要注意的是要靠右對齊,所以不足 7 位的要補上空白。
參考解法
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 
 | #include <bits/stdc++.h>
 using namespace std;
 
 static auto __ = []
 {
 ios_base::sync_with_stdio(0);
 cin.tie(0);
 cout.tie(0);
 return 0;
 }();
 
 string orgin;
 int n;
 int m;
 int Dec;
 list<char> ret;
 
 void split()
 {
 stringstream ss(orgin);
 ss >> orgin >> n >> m;
 }
 
 void cvtToDec()
 {
 for (auto& ch : orgin)
 Dec = Dec * n + (isalpha(ch) ? ch - 'A' + 10 : ch - '0');
 }
 
 void cvtToAns()
 {
 ret.clear();
 
 while (Dec)
 {
 int tmp = Dec % m;
 ret.push_front(tmp < 10 ? tmp + '0' : tmp - 10 + 'A');
 Dec /= m;
 }
 
 if (ret.empty()) ret.push_back('0');
 }
 
 void print()
 {
 if (ret.size() > 7) { cout << "  ERROR\n"; return; }
 
 while (ret.size() < 7) ret.push_front(' ');
 for (auto& ch : ret) cout << ch;
 cout << '\n';
 }
 
 int main()
 {
 while (getline(cin, orgin))
 {
 split();
 cvtToDec();
 cvtToAns();
 print();
 }
 }
 
 |