bitwise operators - Java - Setting a distinct bit of an integer to zero -
here description:
in order stop mad coder evil genius need decipher encrypted message sent minions. message contains several numbers that, when typed supercomputer, launch missile sky blocking out sun, , making people on earth grumpy , sad.
you figured out numbers have modified single digit in binary representation. more specifically, in given number n kth bit right set 0, current value might different. it's write function change kth bit of n 0.
example
for n = 37 , k = 3, output should killkthbit(n, k) = 33.
3710 = 1001012 ~> 1000012 = 3310.
for n = 37 , k = 4, output should be
killkthbit(n, k) = 37.
the 4th bit 0 (looks mad coder forgot encrypt number), answer still 37."
here solution found , cannot understand it:
int killkthbit(int n, int k) { return n & ~(1 << (k - 1)) ; }
can explain solution , syntax?
detailed explanation of function
the expression 1 << (k - 1)
shifts number 1
k-1
times left example 8 bit number , k = 4
:
before shift: 00000001
after shift: 00010000
this marks bit kill. see, 1
shifted fourth position, on position zero. operator ~
negates each bit, meaning 1
becomes 0
, 0
becomes 1
. our example:
before negation: 00010000
after negation: 11101111
at last, &
executes bit-wise and on 2 operands. let say, have number n = 17
, 00010001
in binary. our example is:
00010001 & 11101111 = 00000001
this is, because each bit of both numbers compared and on the same position. positions, both numbers have 1
remain 1
, others set 0
. consequently, position 0 remains 1
.
overall method int killkthbit(int n, int k)
binary operators, sets bit on position k
of number n
0
.
if want learn more topic, can refer documentation bitwise operators.
Comments
Post a Comment