簡単 0件解決済み 正答率0%

銀行口座のルール

預金と引き出しのルールで口座残高を守り、不正な操作を拒否します。

このチャレンジで学べること

  • 状態はメソッド経由でだけ変える
  • 不正な金額と残高超過を拒否する
  • 拒否された操作の数を数える

問題

原文(英語)を表示

Encapsulation はオブジェクトのデータを private に保ち、ルールを守る methods を通してのみ変更できるようにします。銀行口座の残高は deposit と withdraw でしか変えられません。

残高 0 から始め、各 deposit <amount> または withdraw <amount> の operation を処理します。

  • 0 以下の amount は拒否されます。
  • 現在の残高を超える withdrawal は拒否されます。
  • それ以外では残高が変化します。

bank_account_rules(operations) を実装してください。

入力

operations: 順番に並んだ operations です。

出力

[final_balance, rejected_count] を返します。

制約

0 ≤ 操作の数 ≤ 100,000

−10^9 ≤ 金額 ≤ 10^9

例

例 1
入力:
operations = ["deposit 100", "withdraw 30", "withdraw 200"]

期待される出力:
expected = [70, 1]
入力:
std::vector<std::string> operations = {"deposit 100", "withdraw 30", "withdraw 200"};

期待される出力:
std::vector<long long> expected = {70, 1};
入力:
string[] operations = new string[] {"deposit 100", "withdraw 30", "withdraw 200"};

期待される出力:
long[] expected = new long[] {70, 1};

解説

100 − 30 で 70 が残ります。200 の引き出しは口座残高を超えるため拒否されます: [70, 1].

例 2
入力:
operations = ["deposit -5", "withdraw 0", "deposit 10"]

期待される出力:
expected = [10, 2]
入力:
std::vector<std::string> operations = {"deposit -5", "withdraw 0", "deposit 10"};

期待される出力:
std::vector<long long> expected = {10, 2};
入力:
string[] operations = new string[] {"deposit -5", "withdraw 0", "deposit 10"};

期待される出力:
long[] expected = new long[] {10, 2};

解説

負の預金と 0 の引き出しはどちらも拒否されます。最後の預金は成功します: [10, 2].

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

残高は非公開にして、deposit と withdraw の中だけで変えます。

ヒント 2

まず 0 以下の金額を拒否します。

ヒント 3

引き出しで残高がマイナスになってはいけません。

目安の計算量

時間 O(操作の数)、追加メモリ O(1)

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。