Count of Matches in Tournament LeetCode solution in Java

1
class Solution {
2
public int numberOfMatches(int n) {
3
// This is the problem's base case; we know that if n == 1,
4
// the number of matches played must be 0, since the last team left
5
// can't play a match against themselves.
6
if (n == 1) return 0;
7

8
// We declare an int to hold our recursive solution.
9
int res;
10

11
// We initialize res using a recursive call, reducing n
12
// as described in the problem.
13
if (n % 2 == 0) {
14
res = numberOfMatches(n / 2);
15
// After the recursive call is executed, we add the appropriate value to
16
// our solution variable.
17
res += n / 2;
18
} else {
19
res = numberOfMatches((n - 1) / 2 + 1);
20
res += (n - 1) / 2;
21
}
22

23
// Our initial call to numberOfMatches()
24
// will return the total number of matches
25
// added to res in each recursive call.
26
return res;
27
}
28
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0