-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNBIN.cpp
94 lines (74 loc) · 2.15 KB
/
NBIN.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Created by gaurav on 4/18/14.
*/
public class Main {
private static List<Long> preComputedNumbersList = new ArrayList<Long>();
private static final int maxBits = 75;
public static void main(String [] args)
{
preComputeValues();
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
Main Main = new Main();
while(t-->0)
{
long input = scanner.nextLong();
Main.printNthNumberBinaryForm(input);
}
}
public void printNthNumberBinaryForm(long n)
{
// get ith bit number representation for which this n coming
List<Integer> oneBitPosn = new ArrayList<Integer>();
int ibit = getIthBit(n);
long left = n - preComputedNumbersList.get(ibit-1) - 1;
// System.out.println(left + " with bit " + ibit);
oneBitPosn.add(ibit);
while(left > 0)
{
int tempIbit = getIthBit(left);
oneBitPosn.add(tempIbit);
if(tempIbit == 1)
break;
left = left - preComputedNumbersList.get(tempIbit-1) - 1;
}
for(int i = ibit ; i >= 1 ;--i)
{
if( oneBitPosn.contains(i) )
System.out.print(1);
else
System.out.print(0);
}
System.out.println();
}
public int getIthBit(long n)
{
for(int i = 1; i <= maxBits; ++i)
{
if( preComputedNumbersList.get(i) >= n )
return i;
}
return maxBits;
}
public static void preComputeValues()
{
preComputedNumbersList.add(0L);
preComputedNumbersList.add(1L);
preComputedNumbersList.add(2L);
preComputedNumbersList.add(4L);
long prevVal = 4;
for(int i = 4; i <= maxBits; ++i)
{
long temp = prevVal + preComputedNumbersList.get(i-2) + 1;
preComputedNumbersList.add(temp);
// System.out.println(i + " " + temp);
prevVal = temp;
}
}
Main()
{
}
}