java - Implementing bitwise XNOR -
i saw question finding non repeatitive number set contains 1 distict number , rest numberes can repeated number of times. constraint there need find number in single pass using constant memory. {assume positive numbers}.
acheived making function
private static int nonrepeatingelement(int[] set) { int element = 0; (int = 0; < set.length; i++) { element = (element ^ set[i]); system.out.println(element); } return element; }
and working fine.
because of curiosity thought change problem similar constraints.
problem1
thought of set contains elements can occur odd number of time except 1 element occures no of time. for example
{2,5,7,5,7,1,2,7,1,5,2}
consereding logic xnor gives 0 every odd occurence of 1 changed code little like
(int = 0; < set.length; i++) { element = (element ^ set[i]); system.out.println(element); } return ~element;
but didn't work.
problem2
if take elements in set {2,5,7,5,7,1,2,7,5,2} thinking xnoring make every thrice occurence of number 0 , xnoring 1(single occurrence) 0 flip bits of 1.so final result can acheived if flip(~) bits of i'm gettting xnor operation.but doesnt work.
know why semantics going wrong bitwise operation not logical.but if xoring can used finding odd occurance of number isn't there way xnor finding occurrent of number?
i'm not sure feasibility of problem i'm asking out of curiosity forgive ignorance if it's irrelevent in context.
xor
, xnor
commutative. means re-ordering of sequence yield same result.
you know a ^ a
zero. that's how single number abstraction works: a ^ b ^ a
equals a ^ ^ b
equals 0 ^ b
b
.
but a xnor a
not function of a
. it's whole load of 1 bits. therefore can't recover value of a
using a xnor a
, approach not work.
Comments
Post a Comment