1611. 使整数变为 0 的最少操作次数
两种gray转binary的写法,后者简单,前者是纯按gray转binary的描述写的(也不全是,还需要理解一下。。)
class Solution {
public:
int minimumOneBitOperations(int gray) {
if (!gray) return 0;
int head = 1 << int(log2(gray));
return head + minimumOneBitOperations((gray ^ head) ^ (head >> 1));
}
};
class Solution {
public:
int minimumOneBitOperations(int n) {
int ans = 0;
while (n) {
ans ^= n;
n >>= 1;
}
return ans;
}
};
网友评论