Auditions: “Singing Champs” is a famous reality series. The show organizers have planned to roll out the show’s 5th season in the coming month. The auditions for the show is announced at various Cities widely and the organizers have inaugurated the first audition today.
Large mass of people gathered at the venue. Based on the selection procedure for the first level, all the people are made to stand in a queue. Participants who are standing in the even positions of the queue are selected initially. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person.
To help them in the selection procedure, the organizers approached you to write a recursive method for determining the position of that final person in the original queue.
Hence create a class named Position with the following method.
Method Name | Description |
int findPos(int) | This recursive method should return the position(original queue) of that person who is left. |
Create a driver class called Main. In the Main method, obtain input from the user in the console and display the position(original queue) of that person who is left by calling the findPos method present in th Position class.
[Note: Strictly adhere to the Object Oriented Specifications given in the problem statement.
All class names, attribute names and method names should be the same as specified in the problem statement.]
Input Format:
First and only line of the input is an integer N that corresponds to the total number of people who came for the auditions.
Output Format:
Output the position(original queue) of that person who is left.
Refer sample input and output for formatting specifications.
Sample Input 1:
5
Sample Output 1:
4
Sample Input 2:
180
Sample Output 2:
128
Solution
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int pos = findPos(x);
System.out.println(pos);
}
public static int findPos (int x)
{
return (1<<bitlength(x));
}
public static int bitlength(int x)
{
int c=0;
while(x!=0)
{
c++;
x>>=1;
}
return --c;
}
}
#include <bits/stdc++.h>
using namespace std;
int findPos(int n)
{
if (n == 1)
return 1;
return 2 * findPos((int)(n / 2));
}
int main()
{
int n;
cin >> n;
cout << findPos(n);
return 0;
}
Happy Learning – If you require any further information, feel free to contact me.