第一版,会溢出
class Solution {
public:
int insertBits(int N, int M, int i, int j) {
int ret = 0;
for(long long int m = 0;m < i;m++){
ret |= ((1 << m) & N);
}
for(long long int n = j+1;(1 << n) <= N;n++){
ret |= ((1 << n) & N);
}
// for(int k = i;k <= j;k++){
// int h = k-1;
// ret != ((1 << h) & M);
// }
M = M << i;
for(long long int k = 0;k <= j;k++){
ret |= ((1 << k) & M);
}
return ret;
}
};
第二版
通过取反就不用担心把高位变成 0 了。
class Solution {
public int insertBits(int N, int M, int i, int j) {
for(int k = i; k <= j; k++){
N &= ~((long)1<<k);
}
return N|(M<<i);
}
}
作者:xiao-lang-dw
链接:https://leetcode-cn.com/problems/insert-into-bits-lcci/solution/javawei-yun-suan-by-xiao-lang-dw-pww6/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public:
int insertBits(int N, int M, int i, int j) {
for(int k = i;k <= j;k++){
N &= ~((long long)1 << k);
}
return N | (M << i);
}
};