Example 1:
Input: n = 4
Output: 10
Explanation: After the 4th day,
the total is 1 + 2 + 3 + 4 = 10.
Example 2:
Input: n = 10
Output: 37
Explanation: After the 10th day,
the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37.
Notice that on the 2nd Monday, Hercy only puts in $2.
Example 3:
Input: n = 20
Output: 96
Explanation: After the 20th day,
the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) +
(3 + 4 + 5 + 6 + 7 + 8) = 96.
1 2 3 4 5 6 7
|
start
2 3 4 5 6 7 8
|
start+1
class Solution {
public:
int totalMoney(int n) {
int start = 1, j = start, i = 0, out = 0;
while (i < n) {
out += j;
j += 1;
i++;
if (i%7 == 0) {
start += 1;
j = start;
}
}
return out;
}
};
class Solution {
public:
int totalMoney(int n) {
int start = 1, j = start, i = 0, out = 0;
/*
lambda expression
function_pointer = [env var] (params) mutable throw -> return_type {
.....function body ......
};
*/
//CPP11 = lambda
//CPP14 = auto type deduction for the lambda
auto fun = [&]() {
out += j;
j += 1;
i++;
if (i%7 == 0) {
start += 1;
j = start;
}
};
while (i < n) {
fun();
}
return out;
}
};
class Solution {
public:
int totalMoney(int n) {
int start = 1, j = start, i = 0, out = 0;
//CPP17 = capture 3 values from lambda
auto updateCounters = [&]() -> std::tuple<int, int, int> {
out += j;
j += 1;
i++;
if (i % 7 == 0) {
start += 1;
j = start;
}
return std::make_tuple(out, j, i);
};
while (i < n) {
std::tie(out, j, i) = updateCounters();
}
return out;
}
};
class Solution:
def totalMoney(self, n: int) -> int:
start = 1
j = start
i = 0
out = 0
while i < n:
out += j
j += 1
i += 1
if i%7 == 0:
start += 1
j = start
return out
impl Solution {
pub fn total_money(n: i32) -> i32 {
let mut start = 1;
let mut j = start;
let mut i = 0;
let mut out = 0;
while (i < n) {
out += j;
j += 1;
i += 1;
if (i%7 == 0) {
start += 1;
j = start;
}
}
out
}
}
func totalMoney(n int) int {
start := 1
j := start
i := 0
out := 0
for i < n {
out += j
j += 1
i++
if (i%7 == 0) {
start += 1
j = start
}
}
return out
}