#179 Update Bits

题目描述:

Given two 32-bit numbers, N and M, and two bit positions, iand 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 j and 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

Challenge 

Minimum number of operations?

解题思路:

这题的思路应该很多。我想到的一种比较容易想清楚的解法是:先把N中i到j位的bit清零(这个操作可以用一个mask做到),再加上M*2^i即可。这题比较容易出错的地方是要考虑到m或n < 0的情况,这种情况下不能直接做bit operation,应该先用long long的type将m或n存起来,如果<0则加上2^32,改成正数再做上述操作。

Mycode(AC = 22ms):

class Solution {
public:
    /**
     *@param n, m: Two integer
     *@param i, j: Two bit positions
     *return: An integer
     */
    int updateBits(int n, int m, int i, int j) {
        // write your code here
        long long long_n = n, long_m = m;
        if (long_n < 0) {
            long_n += pow(2, 32);
        }
        if (long_m < 0) {
            long_m += pow(2, 32);
        }
        
        // mask = 11111...111
        long long mask = pow(2, 32) - 1;
        int idx = i; // 2
        while (idx <= j) {
            mask -= pow(2, idx); // mask - 2^2 - 2^3... - 2^6
            idx++;
        }
        
        long long ans = mask & long_n; // ans = 10000000000
        ans += long_m * pow(2, i); // ans + 10101 << 2
        
        return (int)(ans > (long long)pow(2, 32) ? ans - (long long)pow(2, 32): ans);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值