LintCode - 更新二进制位
来源:互联网 发布:淘宝事件营销的案例 编辑:程序博客网 时间:2024/06/05 20:53
原题链接: http://www.lintcode.com/zh-cn/problem/update-bits/
给出两个32位的整数N和M,以及两个二进制位的位置i和j。写一个方法来使得N中的第i到j位等于M(M会是N中从第i为开始到第j位的子串)
样例
给出N = (10000000000)2,M = (10101)2, i = 2, j = 6
返回 N = (10001010100)2
分析:
如果是两个二进制的字符串,结果就是遍历数组然后对应的位替换。因此将该题抽象为先得到二进制的字符串,替换之后,将二进制的字符串再次转换为整数
遇到的问题
发现在移位操作有问题,例如flag<<1,在visualstdio和lintcode编译环境中,都无法执行的样子。因此采用flag = flag*2来代替
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 int flag = 1; string str_m = ""; string str_n = ""; while(flag){ if( (m & flag) == 0) str_m+='0'; else{ str_m+='1'; } flag = flag*2; } flag = 1; while(flag){ if( (n & flag) == 0) str_n+='0'; else{ str_n+='1'; } flag = flag*2; } for(int k = i; k <= j; k++){ str_n[k] = str_m[k-i]; } int result = 0; int count = 1; for(int p = 0; p < str_n.length(); p++){ if(str_n[p] == '1') result += count; count*=2; } return result; }};
0 0
- LintCode-更新二进制位
- LintCode - 更新二进制位
- lintcode-更新二进制位-179
- LintCode 更新二进制位
- LintCode:更新二进制位
- LintCode 更新二进制位
- lintcode 更新二进制位
- 中等 更新二进制位 (lintcode)
- LintCode 179-更新二进制位
- LintCode : 更新二进制位
- 更新二进制位-LintCode
- 更新二进制位——LintCode
- 更新二进制位
- 更新二进制位
- 更新二进制位
- 更新二进制位
- 左旋转二进制位-LintCode
- 二进制位
- 玩命牛的成长记录(二十四)——线性渐变和径向渐变
- 1162_奇偶求值
- Spring中 @Autowired标签与 @Resource标签 的区别
- 知识点——网络
- 监控JVM内存?
- LintCode - 更新二进制位
- Codeforces Round #311 (Div. 2) A B C D
- GNU-LIBC源码学习之strlen
- Leetcode_190_Reverse Bits
- IOS开发-06.提示框
- leetcode 69:Sqrt(x)
- 对类的继承的理解
- Android使用Volley保持与服务器的会话
- java jar 打包命令