1688. Number of matches in the match
Give you an integer n, which represents the number of teams in the game. The competition follows a unique format:
If the current number of teams is even, then each team will be paired with another team. A total of n / 2 games are played, and n / 2 teams are generated to enter the next round.
If the current number of teams is an odd number, then a random bye will be made and one team will be promoted, and the remaining teams will be matched. A total of (n-1) / 2 games are played, and (n-1) / 2 + 1 teams are generated to enter the next round.
Returns the number of matches made in the game until the winning team is determined.
示例 1:
输入:n = 7
输出:6
解释:比赛详情:
- 第 1 轮:队伍数 = 7 ,配对次数 = 3 ,4 支队伍晋级。
- 第 2 轮:队伍数 = 4 ,配对次数 = 2 ,2 支队伍晋级。
- 第 3 轮:队伍数 = 2 ,配对次数 = 1 ,决出 1 支获胜队伍。
总配对次数 = 3 + 2 + 1 = 6
示例 2:
输入:n = 14
输出:13
解释:比赛详情:
- 第 1 轮:队伍数 = 14 ,配对次数 = 7 ,7 支队伍晋级。
- 第 2 轮:队伍数 = 7 ,配对次数 = 3 ,4 支队伍晋级。
- 第 3 轮:队伍数 = 4 ,配对次数 = 2 ,2 支队伍晋级。
- 第 4 轮:队伍数 = 2 ,配对次数 = 1 ,决出 1 支获胜队伍。
总配对次数 = 7 + 3 + 2 + 1 = 13
提示:
1 <= n <= 200
Code:
int numberOfMatches(int n){
int sum = 0;
while(n>1)
{
if(n%2==0)
{
sum=sum+n/2;
n=n/2;
continue;
}
else
{
sum=sum+(n-1)/2;
n=(n-1)/2+1;
continue;
}
}
return sum;
}