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

LintCode "Update Bits"

时间:2015-09-18 15:24:44      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

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) {
        if (i == 0 && j == 31) return m;
        
        int cnt = j - i + 1;
        int mask = (1 << cnt) - 1;
        int nn = (n >> i) & mask;
        n ^= (nn << i); // clear
        n |= (m << i); // set
        
        return n;
    }
};

LintCode "Update Bits"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4819040.html

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