Monday 17 August 2015

Survival Strategy

Standard
Ali baba did a trick on the forty thieves and was able to trap them inside a big cave which was the home of wild wolves. The thieves are without any weapons, only the chief of the thieves has knife. With no weapons they will not be able to fight with the wolves, so they decide to kill themselves rather than being eaten alive.
They all decide that they will stand in a circle and they every third person will kill himself but the chief of the thieves does not like this idea and has no intention of killing himself. He calculates where should he stand so that he is the last one left.
HackerMan wants to build a game based on this story, but instead of killing he decides that the participant will leave the game, and instead of every 3rd position it will be every 2nd position. Of course the number of participants will be much more than 40 in this game.
Input
The first line of input is an integer N (1 <= N <= 1000) that specifies the number of test cases. After that every line contains an integer X (5 <= X <= 100000000) which is the number of participants in the game.
Output
For each test case generate a line containing the position of the participant who survives. Assume that the participants have serial numbers from 1 to n and that the counting starts with person 1, i.e., the first person leaving is the one with number 2.

Sample Input
4
5
11
45
23987443
Sample Output
3
7
27
14420455
Explanation
Taking the case of the first test case if there are 5 participants in the circle, the first to go is 2, followed by 4, followed by 1, followed by 5 which leaves 3 at the end.

Time Limit: 2 sec(s) for all input files combined.
Memory Limit: 256 MB
Source Limit: 1024 KB 
 
Code: 
 
import java.util.Scanner;

class TestClass {
    public static void main(String args[] ) throws Exception {
   
        Scanner input = new Scanner(System.in);
        long testCases = input.nextLong();

        for (int i = 0; i < testCases; i++) {
            long participants = input.nextLong();
            long difference = 0;
            long powerOfTwo = 1;

            for (int j = 1; j <= participants; j++) {
                powerOfTwo = (long) Math.pow(2, j);
                if (powerOfTwo >= participants) {
                    difference = powerOfTwo - participants;
                    break;
                }
            }

            if (difference == 0) {
                System.out.println("1");
            } else {
                if (difference == 1) {
                    System.out.println(participants);
                } else {
                    difference--;
                    System.out.println(participants - difference);
                }
            }
        }
   
    }

0 comments:

Post a Comment