程式語言實作練習題 2022.08.13

Ping-Lun Liao
2 min readAug 13, 2022

--

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

第一題:a038: 數字翻轉

a038. 數字翻轉- 高中生程式解題系統

這題常見的解法會類似如下:

也可以用字串來解:

C++程式碼:

  1. #include <iostream>
  2. #include <sstream>
  3. {
  4. string s;
  5. {
  6. short len = s.length ( ) ;
  7. for ( short i = len — 1 ; i >= 0 ; i — )
  8. {
  9. if ( s[i] ! = ‘0’ ) hasZero = false ;
  10. if ( !hasZero ) cout << s[i] ;
  11. }
  12. }
  13. }
用Python 程式語言來解,短短幾行就解決了!這是因為 python 有Slicing語法可用。

Python程式碼:

1 2 3 4import sys for s in sys.stdin: # 輸入數字 print(int(s[::-1])) # 反轉

第二題:a291: nAnB problem

a291. nAnB problem — 高中生程式解題系統

首先需要了解此題的規則,例如測試資料為

8 4 7 5
4
1 2 3 4
8 1 2 4
4 7 5 8
8 4 7 5

輸出結果會是
1234 ==> 0A1B
8124 ==> 1A1B
4758 ==> 0A4B
8475 ==> 4A0B

了解以上的規則後,就可以用比對的方式計算出有多少個 A與多少個 B了。
可用一層迴圈算出幾個 A。
可用兩層迴圈算出幾個 B。

C++ 程式碼:

  1. #include <cstdio>
  2. #include <iostream>
  3. while ( scanf ( “%d %d %d %d”, &answer[ 0 ], &answer[ 1 ], &answer[ 2 ], &answer[ 3 ] ) ! = EOF ) {
  4. scanf ( “%d”, &round) ;
  5. // How many A.
  6. if (guess[guessIdx] == answer[guessIdx] ) {
  7. }
  8. guessIdx++ ;
  9. }
  10. // How Many B.
  11. for ( guessIdx = 0 ; guessIdx < CNT; guessIdx++ ) {
  12. for ( int answerIdx = 0 ; answerIdx < CNT; answerIdx++ ) {
  13. if ( found[answerIdx] == 0 && (guess[guessIdx] == answer[answerIdx] ) && guessIdx ! = answerIdx ) {
  14. break ;
  15. }
  16. }
  17. }
  18. idx++ ;
  19. }
  20. printf ( “%dA%dB\n”, a[idx], b[idx] ) ;
  21. idx++ ;
  22. }
  23. }
  24. }

Originally published at https://yunlinsong.blogspot.com.

--

--

No responses yet