(UVA) Splitting Numbers - Solution

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

The solution below used Bit Manipulation to solve this problem.


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

class Main {
    public void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int n = Integer.parseInt(br.readLine());
        while (n != 0) {
            int[] v = new int[2];
           
            int turn = 0;
            int result = n^(n-1);
            if (result == 1) {
                v[turn] |= result;
                n -= 1;
            }
            else {
                int tmp = (n-1)&n;
                v[turn] |= tmp^n;
                n = (n-1)&n;
            }   
            turn++;
           
           
            while (n > 0) {
                int tmp = (n-1)&n;
                v[turn%2] |= tmp^n;
                n = (n-1)&n;
                turn++;
            }      
           
            bw.write(v[0]+" "+v[1]+"\n");
           
            n = Integer.parseInt(br.readLine());
        }
                                                      
        bw.flush();
        bw.close();
       
        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) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução