2043. 简易银行系统
This commit is contained in:
+63
-18
@@ -1,26 +1,71 @@
|
||||
mod arr;
|
||||
struct Solution {}
|
||||
struct Bank {
|
||||
_balance: Vec<i64>,
|
||||
}
|
||||
|
||||
impl Solution {
|
||||
pub fn number_of_beams(bank: Vec<String>) -> i32 {
|
||||
let mut ans = 0;
|
||||
let mut last_ones = 0;
|
||||
for i in 0..bank.len() {
|
||||
let new_ones = bank[i].chars().fold(0,|last, c| last + if c == '1'{1}else {0});
|
||||
if new_ones == 0 {
|
||||
continue;
|
||||
}
|
||||
ans += last_ones * new_ones;
|
||||
last_ones = new_ones;
|
||||
|
||||
/**
|
||||
* `&self` means the method takes an immutable reference.
|
||||
* If you need a mutable reference, change it to `&mut self` instead.
|
||||
*/
|
||||
impl Bank {
|
||||
|
||||
fn new(balance: Vec<i64>) -> Self {
|
||||
Bank { _balance: balance }
|
||||
}
|
||||
|
||||
fn valid(&self, account: i32,money: i64) -> bool {
|
||||
account > 0 && account as usize <= self._balance.len() && self._balance[account as usize - 1] >= money
|
||||
}
|
||||
fn transfer(&mut self, account1: i32, account2: i32, money: i64) -> bool {
|
||||
if !self.valid(account1, money) {
|
||||
return false;
|
||||
}
|
||||
self._balance[account1 as usize - 1] -= money;
|
||||
self._balance[account2 as usize - 1] += money;
|
||||
true
|
||||
}
|
||||
|
||||
fn deposit(&mut self, account: i32, money: i64) -> bool {
|
||||
if !self.valid(account, 0) {
|
||||
return false;
|
||||
}
|
||||
self._balance[account as usize - 1] += money;
|
||||
true
|
||||
}
|
||||
|
||||
fn withdraw(&mut self, account: i32, money: i64) -> bool {
|
||||
if !self.valid(account, money) {
|
||||
false
|
||||
} else {
|
||||
self._balance[account as usize - 1] -= money;
|
||||
true
|
||||
}
|
||||
ans
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Your Bank object will be instantiated and called as such:
|
||||
* let obj = Bank::new(balance);
|
||||
* let ret_1: bool = obj.transfer(account1, account2, money);
|
||||
* let ret_2: bool = obj.deposit(account, money);
|
||||
* let ret_3: bool = obj.withdraw(account, money);
|
||||
*/
|
||||
|
||||
fn main() {
|
||||
let src = vec!["011001", "000000", "010100", "001000"]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
println!("{:?}", Solution::number_of_beams(src));
|
||||
let oper = ["withdraw", "transfer", "deposit", "transfer", "withdraw"];
|
||||
let val = arr::make_matrix("[[3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]");
|
||||
//输出:
|
||||
//[true, true, true, false, false]
|
||||
let mut bank = Bank::new(vec![10, 100, 20, 50, 30]);
|
||||
for i in 0..oper.len() {
|
||||
let result = match oper[i] {
|
||||
"withdraw" => bank.withdraw(val[i][0], val[i][1] as i64),
|
||||
"transfer" => bank.transfer(val[i][0], val[i][1], val[i][2] as i64),
|
||||
"deposit" => bank.deposit(val[i][0], val[i][1] as i64),
|
||||
_ => false,
|
||||
};
|
||||
println!("{}", result);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user