(UVA) Dropping Balls - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=620

The ball can only go to two directions, left or right. If the ball's number is even, it goes to the left, but if it is odd, the ball goes to the right. Then, we know in which node the ball is through the operations: node = node*2 and node = node*2+1.


import java.io.*;
import java.util.*;

class Main {
    public static void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
       
        int numTests = sc.nextInt();
        for (int i = 0; i < numTests; i++) {
            int depth = sc.nextInt();
            int ball = sc.nextInt();
           
            int node = 1;
            int newBall = ball-1;
            for (int j = 0; j < depth-1; j++) {
                if (newBall%2 == 0) {
                    node = node*2;
                }
                else {
                    node = node*2+1;
                }
                newBall /= 2;
            }
           
            System.out.println(node);
        }
       
        int end = sc.nextInt();
                                       
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução