add: 220318-CN [cpp]

This commit is contained in:
Lam Haoyin 2022-03-19 02:04:19 +08:00
parent b8c6b0eab4
commit 2de43036d4
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 49 additions and 1 deletions

48
cpp/2203/220318-CN.cpp Normal file
View File

@ -0,0 +1,48 @@
#include <vector>
/**
* 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<long long> balance;
public:
explicit Bank(std::vector<long long> 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;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220318.cpp)
ADD_EXECUTABLE(2203 220318-CN.cpp)