CPE 一顆星選集 49 道必考題
題目連結:https://zerojudge.tw/ShowProblem?problemid=d672
內容
使用遞迴方法判斷一數 N (可能很大)是否為 9 的倍數,並且求出此遞迴的深度。
遞迴方法(假設 N = 837):
8 + 3 + 7 -> 18 深度:1
1 + 8 -> 9 深度:2(結束)。
當 N = 0 代表輸入結束。
範例輸入
999999999999999999999
9
9999999999999999999999999999998
837
0
範例輸出
999999999999999999999 is a multiple of 9 and has 9-degree 3.
9 is a multiple of 9 and has 9-degree 1.
9999999999999999999999999999998 is not a multiple of 9.
837 is a multiple of 9 and has 9-degree 2.
想法
使用 string 讀取輸入,先進行第一次的運算,得到的數值一定為 int 範圍,之後每次得到新數值都將其轉為 string 型態方便操作(利用 stringstream 進行轉換),直到數值等於 9 。
像是 999999999999999999999 (string 型態) 即可用字元方式分別取出,得到新數值 189 (int 型態),此為一個深度。
接者將其轉為 string 型態,189 (string 型態),用字元方式分別取出,得到新數值 18 (int 型態)。此為第二個深度。
18 (int 型態) -> 18 (string 型態),得到 9 (int 型態),此為第三個深度。
程式碼
C++
1 |
|