跳到主要内容

2240.买钢笔和铅笔的方案数

链接:2240.买钢笔和铅笔的方案数
难度:Medium
标签:数学、枚举
简介:给你一个整数 total ,表示你拥有的总钱数。同时给你两个整数 cost1 和 cost2 ,分别表示一支钢笔和一支铅笔的价格。你可以花费你部分或者全部的钱,去买任意数目的两种笔。请你返回购买钢笔和铅笔的 不同方案数目 。

题解 1 - python

  • 编辑时间:2023-09-01
  • 执行用时:664ms
  • 内存消耗:16MB
  • 编程语言:python
  • 解法介绍:同上。
class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
idx1 = res = 0
while idx1 * cost1 <= total:
res += 1 + (total - idx1 * cost1) // cost2
idx1 += 1
return res

题解 2 - rust

  • 编辑时间:2023-09-01
  • 执行用时:12ms
  • 内存消耗:2.04MB
  • 编程语言:rust
  • 解法介绍:同上。
impl Solution {
pub fn ways_to_buy_pens_pencils(total: i32, cost1: i32, cost2: i32) -> i64 {
let (total, cost1, cost2, mut idx1, mut res) = (
total as i64, cost1 as i64, cost2 as i64,
0i64, 0i64
);
while idx1 * cost1 <= total {
res += 1 + (total - cost1 * idx1) / cost2;
idx1 += 1;
}
res
}
}

题解 3 - cpp

  • 编辑时间:2023-09-01
  • 执行用时:16ms
  • 内存消耗:5.9MB
  • 编程语言:cpp
  • 解法介绍:枚举。
class Solution {
public:
long long waysToBuyPensPencils(int total, int cost1, int cost2) {
long long idx1 = 0, res = 0;
while (idx1 * cost1 <= total) {
res += 1 + (total - idx1 * cost1) / cost2;
idx1 += 1;
}
return res;
}
};