The Problem
You will be given a decimal number. You will have to convert it to its ternary (Base 3) equivalent.
Input
The input file contains at most 100 lines of inputs. Each line contains a non-negative decimal integer N(N<1000000001). Input is terminated by a line containing a negative value. This line should not be processed.
Output
For each line of input produce one line of output. This line contains the ternary equivalent of decimal value N.
Sample Input
10
100
1000
-1
Sample Output
101
10201
1101001
解題思考
這一題要將十進位數字轉成三進位。所以,我們要利用一個迴圈來得出這個答案。
在每一輪迴圈中,我們將輸入的數字 n / 3,在第 i 輪迴圈所得的餘數就代表此三進位數字的第 i 位數字。一直重複相同的步驟,直到 n 變為零為止。
得出每一位數字之後,再將結果輸出,就是答案了。
參考解答(C++)
#include <iostream> #include <string> using namespace std; int main(void) { while (1) { int n; cin >> n; if (n < 0) { break; } string ans; do { ans = static_cast<char>(n % 3 + '0') + ans; n /= 3; } while (n); cout << ans << endl; } #ifndef ONLINE_JUDGE system("pause"); #endif }
0 回覆:
張貼留言