程式語言實作練習題 2022.08.13
2 min readAug 13, 2022
若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。
第一題:a038: 數字翻轉
這題常見的解法會類似如下:
也可以用字串來解:
C++程式碼:
- #include <iostream>
- #include <sstream>
- {
- string s;
- {
- short len = s.length ( ) ;
- for ( short i = len — 1 ; i >= 0 ; i — )
- {
- if ( s[i] ! = ‘0’ ) hasZero = false ;
- if ( !hasZero ) cout << s[i] ;
- }
- }
- }
用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++ 程式碼:
- #include <cstdio>
- #include <iostream>
- while ( scanf ( “%d %d %d %d”, &answer[ 0 ], &answer[ 1 ], &answer[ 2 ], &answer[ 3 ] ) ! = EOF ) {
- scanf ( “%d”, &round) ;
- // How many A.
- if (guess[guessIdx] == answer[guessIdx] ) {
- }
- guessIdx++ ;
- }
- // How Many B.
- for ( guessIdx = 0 ; guessIdx < CNT; guessIdx++ ) {
- for ( int answerIdx = 0 ; answerIdx < CNT; answerIdx++ ) {
- if ( found[answerIdx] == 0 && (guess[guessIdx] == answer[answerIdx] ) && guessIdx ! = answerIdx ) {
- break ;
- }
- }
- }
- idx++ ;
- }
- printf ( “%dA%dB\n”, a[idx], b[idx] ) ;
- idx++ ;
- }
- }
- }
Originally published at https://yunlinsong.blogspot.com.