# UVa 355 ### 題目連結:[UVa355](http://domen111.github.io/UVa-Easy-Viewer/?355) ### [參考1](http://chchwy.blogspot.com/2010/01/acmuva-355-bases-are-loaded.html) :::spoiler sample code ```cpp= #include<iostream> #include<algorithm> using namespace std; inline int CharToDigit(char c) { if ( isdigit(c) ) return c - '0'; return c - 'A' + 10; } inline char DigitToChar(int n) { return "0123456789ABCDEF"[n]; } bool checkIllegal(int base1, string& in ) { for (int i = 0; i < in.length(); ++i) if ( CharToDigit(in[i]) >= base1 ) return true; return false; } /* convert string 'in' to int 'value'. */ long long parseValue( int base1, string& in ) { if ( checkIllegal(base1, in) ) return -1; long long value = 0; long long curBase = 1; for (int i = in.length() - 1; i >= 0; --i) { value += CharToDigit(in[i]) * curBase; curBase *= base1; } return value; } /* convert int 'value' to string 'out' */ string toBase( int base2, long long value ) { if (value == 0) return "0"; string out; while ( value > 0 ) { out += DigitToChar( value % base2 ); value /= base2; } reverse(out.begin(), out.end()); return out; } int main() { #ifndef ONLINE_JUDGE freopen("355.in", "r", stdin); #endif int base1, base2; string in; while ( cin >> base1 >> base2 >> in ) { long long value = parseValue(base1, in); if ( value < 0 ) //wrong { cout << in << " is an illegal base " << base1 << " number\n"; continue; } cout << in << " base " << base1 << " = " << toBase(base2, value) << " base " << base2 << "\n"; } return 0; } ``` ::: ### [參考2](http://onlinejudgesolution.blogspot.com/2017/05/uva-solution-355-bases-are-loaded.html) :::spoiler sample code ```cpp= #include <stdio.h> int main() { int a, b; char s[20]; while(scanf("%d %d %s", &a, &b, s) == 3) { int i, flag = 0; long long dec = 0, base = 1; for(i = 0; s[i]; i++) { dec *= a; if(s[i] >= '0' && s[i] <= '9') { if(s[i]-'0' >= a) { flag = 1; } else { dec += s[i]-'0'; } } else { if(s[i]-'A'+10 >= a) { flag = 1; } else { dec += (s[i]-'A'+10); } } } if(flag) { printf("%s is an illegal base %d number\n", s, a); } else { long long c[50] = {}, ct = -1; while(dec) { c[++ct] = dec%b; dec /= b; } if(ct < 0) ct = 0; printf("%s base %d = ", s, a); while(ct >= 0) { printf("%c", c[ct] <= 9 ? c[ct]+'0' : c[ct]-10+'A'); ct--; } printf(" base %d\n", b); } } return 0; } ``` ::: ### 題述: #### 寫一個程式做進位制之間的轉換(2進位到16進位)。其中A代表10,B代表11......,F代表15。 #### 每組測試資料一列,有3個值。第一個值為一個正整數m,代表要轉換的這個數是幾進位的數。第二個值為一個正整數n,代表要把這個數轉換成幾進位的數。第三個值就是要轉換的數(m進位),這個值最長不會超過10個字元的長度,且有可能在m進位之下是不正確的(例如Sample Input中的第二列,126不是一個正確的5進位數)。 #### 以Sample Input的第一列為例說明:要把2進位表示法的10101轉換成10進位的表示法。 ### c++ code: ```cpp= ``` :::success **``sample input``** 2 10 10101 5 3 126 15 11 A4C 5 15 0 ::: :::success **``sample output``** 10101 base 2 = 21 base 10 126 is an illegal base 5 number A4C base 15 = 1821 base 11 0 base 5 = 0 base 15 ::: #### [返回首頁](https://hackmd.io/@fkleofk/APCS#355) ###### tags: `APCS選修` `C++` `UVa`