-
Notifications
You must be signed in to change notification settings - Fork 0
/
BITPLAY.cpp
77 lines (67 loc) · 1.04 KB
/
BITPLAY.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
#include<stdio.h>
#include<bitset>
#include<string>
#include<cstring>
using namespace std;
string binaryCalc(long num)
{
string binary = bitset<50>(num).to_string(); //to binary
return binary;
}
long decimalCalc(string binary)
{
long decimal = std::bitset<50>(binary).to_ulong();
return decimal;
}
int main()
{
int T,K,i;
long N,counter=0;
string binaryString;
char binary[50];
scanf("%d",&T);
while(T--)
{
scanf("%ld %d",&N,&K);
if(K==0)
{
printf("-1\n");
continue;
}
if(N%2==0)
N--;
while(N>=1)
{
counter=0;
binaryString=binaryCalc(N);
strcpy(binary,binaryString.c_str());
for(i=0;i<sizeof(binary);i++)
if(binary[i]=='1'){
counter++;
}
if(counter<=K)
{
printf("%ld\n",N);
break;
}
else
{
i=sizeof(binary)-2; //i=48 -> (LSB-1)th bit
while(counter>K)
{
if(binary[i]=='1')
{
binary[i]='0';
counter--;
}
i--;
}
printf("%ld\n",decimalCalc(binary));
break;
}
}
if(N<1)
printf("-1\n");
}
return 0;
}