From 2de43036d4b09573faa88ba699e852085d654a39 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Sat, 19 Mar 2022 02:04:19 +0800 Subject: [PATCH] add: 220318-CN [cpp] --- cpp/2203/220318-CN.cpp | 48 +++++++++++++++++++++++++++++++++++++++++ cpp/2203/CMakeLists.txt | 2 +- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 cpp/2203/220318-CN.cpp diff --git a/cpp/2203/220318-CN.cpp b/cpp/2203/220318-CN.cpp new file mode 100644 index 0000000..1e548e0 --- /dev/null +++ b/cpp/2203/220318-CN.cpp @@ -0,0 +1,48 @@ +#include + +/** + * 2043. Simple Bank System + * + * You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initial balance of balance[i]. + * + * Execute all the valid transactions. A transaction is valid if: + * + * The given account number(s) are between 1 and n, and + * The amount of money withdrawn or transferred from is less than or equal to the balance of the account. + * Implement the Bank class: + * + * Bank(long[] balance) Initializes the object with the 0-indexed integer array balance. + * boolean transfer(int account1, int account2, long money) Transfers money dollars from the account numbered account1 to the account numbered account2. Return true if the transaction was successful, false otherwise. + * boolean deposit(int account, long money) Deposit money dollars into the account numbered account. Return true if the transaction was successful, false otherwise. + * boolean withdraw(int account, long money) Withdraw money dollars from the account numbered account. Return true if the transaction was successful, false otherwise. + */ + +class Bank { +private: + std::vector balance; +public: + explicit Bank(std::vector b) : balance(std::move(b)) {} + + bool transfer(int a1, int a2, long long m) { + if (a1 < 1 || a1 > balance.size() || a2 < 1 || a2 > balance.size() || balance[a1 - 1] < m) + return false; + balance[a1 - 1] -= m; + balance[a2 - 1] += m; + return true; + } + + bool deposit(int a, long long m) { + if (a >= 1 && a <= balance.size()) + balance[a - 1] += m; + else + return false; + return true; + } + + bool withdraw(int a, long long m) { + if (a < 1 || a > balance.size() || balance[a - 1] < m) + return false; + balance[a - 1] -= m; + return true; + } +}; diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index 18621ba..fb1f85c 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220318.cpp) +ADD_EXECUTABLE(2203 220318-CN.cpp)