c++ - bit operation AND -
it leetcode problem. given array of numbers nums, in 2 elements appear once , other elements appear twice. find 2 elements appear once.
for example: given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. code is:
class solution { public: vector<int> singlenumber(vector<int>& nums) { int axorb=0; for(auto i:nums) axorb=axorb^i; int differbit=(axorb&(axorb-1))^axorb; int group3=0, group5=0; for(auto i:nums)
if(differbit&i!=0) group5=group5^i;
else group3=group3^i; return vector<int>{group3,group5}; } };
submission result wrong answer.
input:[0,0,1,2] output:[3,0] expected:[1,2]
but if change highlighted part
if(differbit&i) group5=group5^i;
it accepted. spent lot of time thinking still have no idea. maybe type conversion happened? thanks
this has operator precedence.
because in c && , ||
operators added late given low priority wouldn't break legacy programs.
this stack overflow question has answer why:
from forum: http://bytes.com/topic/c/answers/167377-operator-precedence
the && , || operators added later "short-circuiting" behavior. dennis ritchie admits in retrospect precedence of bitwise operators should have been changed when logical operators added. several hundred kilobytes of c source code in existence @ point , installed base of 3 computers, dennis thought big of change in c language...
here a table showing operator precedence.
showing !=
@ higher priority &
.
as can see bitwise &
lower !=
on table, code doing following:
if ( differbit & (i!=0) )
instead of assume meant do:
if ( (differbit & i) != 0 )
Comments
Post a Comment