若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。
If you like this post, please click the ads on the blog or buy me a coffee. Thank you very much.
第一題:a038: 數字翻轉
C++程式碼:
- #include <iostream>
- #include <sstream>
- using namespace std;
- int main()
- {
- string s;
- while(cin >> s)
- {
- short len = s.length();
- bool hasZero = true;
- for(short i = len - 1; i >= 0; i--)
- {
- if( s[i] != '0' ) hasZero = false;
- if( !hasZero ) cout << s[i];
- }
- cout << endl;
- }
- return 0;
- }
用Python 程式語言來解,短短幾行就解決了!這是因為 python 有Slicing語法可用。
Python程式碼:
1 2 3 4 | import 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>
- using namespace std;
- int main() {
- int CNT = 4;
- int answer[CNT];
- int guess[CNT];
- int idx = 0;
- int round = 0;
- while( scanf("%d %d %d %d", &answer[0], &answer[1], &answer[2], &answer[3])!=EOF ) {
- scanf("%d", &round);
- int a[round] = { 0 };
- int b[round] = { 0 };
- idx = 0;
- while( idx < round ) {
- int guessIdx = 0;
- int found[CNT] = { 0 };
- while( guessIdx < CNT ) {
- scanf("%d", &guess[guessIdx]);
- // How many A.
- if(guess[guessIdx] == answer[guessIdx]) {
- a[idx]++;
- found[guessIdx] = 1;
- } else {
- found[guessIdx] = 0;
- }
- guessIdx++;
- }
- // How Many B.
- for( guessIdx = 0; guessIdx < CNT; guessIdx++) {
- if( found[guessIdx] != 1 )
- for(int answerIdx = 0; answerIdx < CNT; answerIdx++) {
- if( found[answerIdx] == 0 && (guess[guessIdx] == answer[answerIdx]) && guessIdx != answerIdx ) {
- b[idx]++;
- found[answerIdx] = 2;
- break;
- }
- }
- }
- idx++;
- }
- idx = 0;
- while( idx < round ) {
- printf("%dA%dB\n", a[idx], b[idx]);
- idx++;
- }
- }
- return 0;
- }
沒有留言:
張貼留言