Skip to content

Latest commit

 

History

History
139 lines (119 loc) · 3.34 KB

_1518. Water Bottles.md

File metadata and controls

139 lines (119 loc) · 3.34 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : July 07, 2024

Last updated : July 07, 2024


Related Topics : Math, Simulation

Acceptance Rate : 70.99 %


n=9, k=3
13 = 9 + 3 + 1

n=15, k=4
ans = 15 + (15//4 + 15 % 4) + ...
    = 15 + ...
    = 19
    
(n bottles) + (n // k new bottles from trade) 
            + ((n // k + n % k) // k new bottles from 2nd round of trading)
            + ((n // k + n % k) // k + (n // k + n % k) % k) // k
            + ...

n = k * m + r1
m = k * n + r2
n = k * o + r3
...

(k * m) + ...

Solutions

Python

class Solution:
    def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
        output = 0
        while numBottles >= numExchange :
            output += numBottles - numBottles % numExchange
            numBottles = numBottles % numExchange + numBottles // numExchange
        output += numBottles
        return output
class Solution:
    def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
        return numBottles + (numBottles - 1) // (numExchange - 1)
    

C

int numWaterBottles(int numBottles, int numExchange) {
    return numBottles + (numBottles - 1) / (numExchange - 1);
}

C++

class Solution {
public:
    int numWaterBottles(int numBottles, int numExchange) {
        return numBottles + (numBottles - 1) / (numExchange - 1);
    }
};

C#

public class Solution {
    public int NumWaterBottles(int numBottles, int numExchange) {
        return numBottles + (numBottles - 1) / (numExchange - 1);
    }
}

Java

class Solution {
    public int numWaterBottles(int numBottles, int numExchange) {
        return numBottles + (numBottles - 1) / (numExchange - 1);
    }
}

JavaScript

/**
 * @param {number} numBottles
 * @param {number} numExchange
 * @return {number}
 */
var numWaterBottles = function(numBottles, numExchange) {
    return numBottles + Math.floor((numBottles - 1) / (numExchange - 1));
};

TypeScript

function numWaterBottles(numBottles: number, numExchange: number): number {
    return numBottles + Math.floor((numBottles - 1) / (numExchange - 1));
};