carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1518:换水问题(water-bottles) #238

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

超市正在促销,你可以用 numExchange 个空水瓶从超市兑换一瓶水。最开始,你一共购入了 numBottles 瓶水。

如果喝掉了水瓶中的水,那么水瓶就会变成空的。

给你两个整数 numBottles 和 numExchange ,返回你 最多 可以喝到多少瓶水。

 

示例 1:

image

输入:numBottles = 9, numExchange = 3 输出:13 解释:你可以用 3 个空瓶兑换 1 瓶水。 所以最多能喝到 9 + 3 + 1 = 13 瓶水。

示例 2:

image

输入:numBottles = 15, numExchange = 4 输出:19 解释:你可以用 4 个空瓶兑换 1 瓶水。 所以最多能喝到 15 + 3 + 1 = 19 瓶水。  

 

提示:

1 <= numBottles <= 100 2 <= numExchange <= 100

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/water-bottles

carloscn commented 1 year ago

问题分析

pub fn num_water_bottles(num_bottles: i32, num_exchange: i32) -> i32
{
    if num_bottles < 1 || num_exchange < 1 {
        return 0;
    }

    let mut ret:i32 = num_bottles;
    let mut count_empty:i32 = num_bottles;
    let mut count_full:i32;

    while count_empty >= num_exchange {
        let t = count_empty;
        count_full = t / num_exchange;
        count_empty = t % num_exchange + count_full;
        ret += count_full;
    }

    return ret;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/554845 https://github.com/carloscn/structstudy/commit/876bbd0322f37058654720f54f60c74ad566f856