【題目描述】
Given two?32-bit numbers,N?and?M, and two bit positions,i?and?j. Write a method to set all bits between?i?and?j?in?N?equal to?M(e g ,M?becomes a ?substring of?N?located at?i ?and starting at?j)
Notice:In the function, the numbers?N?and?M?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)的左邊部分,然后獲得掩碼的右半部分,最后左右按位或即為最終結果。
【參考答案】