[英]I fail to understand the solution of a equation which says that find smallest number such that x plus y is equals x bitwise OR y
The problem is to find kth smallest number(y) which satisfies the following equations x + y = x | 问题是找到满足以下等式x + y = x |的第k个最小数(y)。 y .
。
eg: x = 5 kthSmallest = 1 gives y = 2 as 5+2 = 5 | 例如:x = 5 kthSmallest = 1给出y = 2,因为5 + 2 = 5 | 2
2
I coded it using the basic approach 我用基本方法编码
long kthPlusOrSolutionMine(int x, int k){
int kthSolution = 1;
for(int i=0;i>=0 ; i++ ){
int rhs = x | i;
int lhs = x + i;
if(rhs == lhs){
kthSolution++;
if(kthSolution == k)
return i;
}
return 0;
}
}
However I found another solution of the same problem but I can't understand it completely. 但是我找到了相同问题的另一种解决方案,但我无法完全理解。
long kthPlusOrSolution(int _x, int k) {
long x = _x;
long y=0,t;
for(t=1; k; t=t<<1, k=k>>1){
//cout << "t is " << t << " x is " << x << " k is " << k <<endl;
//cout << (t&x) << endl;
while(t&x)
t=t<<1;
if(k&1)
y = y|t;
}
return y;
}
Can somebody please help me in understanding that how does it works. 有人可以帮我了解它是如何工作的。
Bitwise, you can compare the truth table of addition and OR (C is the addition carry) : 按位,您可以比较加法和OR的真值表(C是加法进位):
A B + C | A+B==A|B
0 0 0 0 0 yep
1 0 1 0 1 yep
0 1 1 0 1 yep
1 1 0 1 1 nope
So you can say that 所以你可以说
Let's number the bits of y that are allowed to vary from 0 to I. 让我们对y的允许从0到I变化的位进行编号。
x 0 0 1 0 0 1 1
i 3 2 - 1 0 - -
Note that if we call Y i a number with the i th bit set to 1, Y i is the solution number 2 i +1 of the equation. 需要注意的是,如果我们所说的Ÿ 我与第 i 个若干个位设置为1,Y i是解决数方程2 我 +1。
for instance: 例如:
x = 010011
y 0-00--
y1 = 0-01-- 2nd
y2 = 0-10-- 3rd
0-11--
y3 = 1-00-- 5th
1-01--
1-10--
1-11--
y4 =10-00-- 9th
Also note that the rank difference between a solution with the i th bit set to zero and the same bit set to 1 is 2 i . 还要注意,与第 i 个的溶液之间的级差比特被设置为零并设置为1相同的比特是2 I。
example: the bit of rank 2 is varying 例如:等级2的位在变化
0-00-- 1st
1-00-- 5th
difference in rank: 2 2 = 4 等级差异:2 2 = 4
This means that setting the i th bit of y
to 1 skips 2 i solutions . 这意味着第 i 个的位设置
y
1只跳过2级I的解决方案 。
That is the magic property that fuels the algorithm. 那就是为算法加油的神奇属性。
during each loop, t
is set to the i th bit of x
(eg if x
= 11, successive values of t
will be 4, 8, 16 etc) 在每个循环中,将
t
设置为x
第 i位(例如,如果x
= 11,则t
连续值将为4、8、16等)
k
is decomposed in powers of 2. During each loop, the n th bit of k in base 2 is examined, and each time y
is updated, 2 n solutions are eliminated using our magic property. k
分解为2的幂。在每个循环中,检查以2为底的k的第 n位,并且每次更新y
,使用我们的魔术特性消除2 n个解。
exemple: if k = 5 (1001b) 范例:如果k = 5(1001b)
1st loop k = 5 -> eliminate 2^0 = 1 solution
2nd loop k = 2 -> does nothing
3rd look k = 1 -> eliminate 2^2 = 4 solutions
at exit, y
is set to the 5th solution. 在出口处,
y
设置为第5个解。
Or more precisely, the 5th solution different from 0, 更确切地说,第5个解不同于0,
which is the 6th if you count zero as a (trivial) solution. 如果您将零视为(平凡的)解决方案,则为第六。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.