You are given an integer n
, the number of teams in a tournament that has strange rules:
- If the current number of teams is even, each team gets paired with another team. A total of
n / 2
matches are played, andn / 2
teams advance to the next round. - If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of
(n - 1) / 2
matches are played, and(n - 1) / 2 + 1
teams advance to the next round.
Find the number of matches played in the tournament until a winner is decided.
Example:
Input: n= 7 Output: 6
Approach
Java
public class CountMatchesTournament {public static void main(String[] args) {int n = 7;System.out.println(numberOfMatches(n));}static int numberOfMatches(int n) {int ans = 0;while (n > 1) {if (n % 2 != 0) {ans += (n - 1) / 2;n = (n - 1) / 2 + 1;} else {ans += n / 2;n = n / 2;}}return ans;}}
C++
#include <bits/stdc++.h>using namespace std;int numberOfMatches(int n){int ans=0;while(n>1){if(n&1){ans+=(n-1)/2;n=(n-1)/2+1;}else{ans+=n/2;n=n/2;}}return ans;}int main(){int n=7;cout<<numberOfMatches(n);return 0;}
No comments:
Post a Comment