BitwiseEquations (SRM 430 Div2 500)

BitwiseEquations (SRM 430 Div2 500)

题目链接: http://www.topcoder.com/stat?c=problem_statement&pm=9921&rd=13521

x+y=x|y.
二进制加法1+0=1|0. 当而仅当x,y的二进制表示中,x的'1'位不与y的'1'对应,这个等式就成立.
所以,对于x中为1的位,y只能为0,对于x中为0的位,y相应位可以任意.
要求第k个y,很显然,把k的二进制表示填充到x的0位中去,即可.

    class  BitwiseEquations
              { 
              
public
              
long   long  kthPlusOrSolution( int  _x,  int  k) 
                  {                 
                  
long   long  result;
                  
long   long  mask  =   1 ;
                  
long   long  x  =  _x;
                  result 
=   0 ;
                  
                  
for ( int  i = 0 ;i < 64 && k != 0 ; ++ i){
                      
if ((mask & x) == 0 ){
                            result
|= ((k & 1 ) * mask);
                            k
>>= 1 ;
                      }
                      mask
<<= 1 ;
                  } 
                  
return  result;
              }
}




你可能感兴趣的:(BitwiseEquations (SRM 430 Div2 500))