Lintcode179 Update Bits solution 题解

【题目描述】

Given two 32-bit numbers,and M, and two bit positions,and j. Write a method to set all bits between and in equal to M(e g ,becomes a  substring of located at i  and starting at j)

Notice:In the function, the numbers and will given in decimal, you should also return a decimal number.

给出两个32位的整数N和M,以及两个二进制位的位置i和j。写一个方法来使得N中的第i到j位等于M(M会是N中从第i为开始到第j位的子串)

【注】在函数中,n和m的数字将以十进制形式给出,还应该返回一个十进制数。

【题目链接】

www.lintcode.com/en/problem/update-bits/

【题目解析】

此题需要借用掩码操作。大致步骤如下:

得到第i位到第j位的比特位为0,而其他位均为1的掩码mask。

使用mask与 N 进行按位与,清零 N 的第i位到第j位。

对 M 右移i位,将 M 放到 N 中指定的位置。

返回 N | M 按位或的结果。

获得掩码mask的过程:先获得掩码(1111…000…111)的左边部分,然后获得掩码的右半部分,最后左右按位或即为最终结果。

【参考答案】

www.jiuzhang.com/solutions/update-bits/

你可能感兴趣的:(Lintcode179 Update Bits solution 题解)