码迷,mamicode.com
首页 > 其他好文 > 详细

Update Bits

时间:2016-07-20 06:31:45      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:

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.

Clarification

You can assume that the bits j through i have enough space to fit all of M. That is, if M=10011, you can assume that there are at least 5 bits between jand i. You would not, for example, have j=3 and i=2, because M could not fully fit between bit 3 and bit 2.

Example

Given N=(10000000000)2M=(10101)2i=2j=6

return N=(10001010100)2

分析:http://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/72988

大致步骤如下:

  1. 得到第i位到第j位的比特位为0,而其他位均为1的掩码mask
  2. 使用mask与 N 进行按位与,清零 N 的第i位到第j位。
  3. 对 M 右移i位,将 M 放到 N 中指定的位置。
  4. 返回 N | M 按位或的结果。

获得掩码mask的过程可参考 CTCI 书中的方法,先获得掩码(1111...000...111)的左边部分,然后获得掩码的右半部分,最后左右按位或即为最终结果。

 1 class Solution {
 2 public:
 3     /**
 4      *@param n, m: Two integer
 5      *@param i, j: Two bit positions
 6      *return: An integer
 7      */
 8     int updateBits(int n, int m, int i, int j) {
 9         // write your code here
10         int ones = ~0;
11         int mask = 0;
12         if (j < 31) {
13             int left = ones << (j + 1);
14             int right = ((1 << i) - 1);
15             mask = left | right;
16         } else {
17             mask = (1 << i) - 1;
18         }
19 
20         return (n & mask) | (m << i);
21     }
22 };

 

Update Bits

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5686916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!