5.1
来源:互联网 发布:知乎年度吐槽精选 编辑:程序博客网 时间:2024/06/05 00:38
Topic 5.1 You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all 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: input: N=10000000000, M=10011, i=2, j=6; Output: N=10001001100
Three steps:
1. Clear the bits j through i in N -----do this with a mask
2. Shift M so that it lines up with bits j through i
3. Merge M and N
import java.math.BigInteger;public class c5_1 {public static int updateBits(int n, int m, int i, int j) {if (i >= 32 || j < i) {return 0;}/* Create a mask to clear bits i through j in n/* EXAMPLE: i = 2, j = 4. Result should be 11100011. * (Using 8 bits for this example. This is obviously not actually 8 bits.) 要让第i到j位为0,其他位为1*/int allOnes = ~0; // allOnes = 11111111//这三句有意思int left = allOnes << (j + 1); // 1s through position j, then 0s. left = 11100000 int right = ((1 << i) - 1); // 1’s after position i. right = 00000011int mask = left | right; /* Clear i through j, then put m in there */int n_cleared = n & mask; // Clear bits j through i.int m_shifted = m << i; // Move m into correct position.return n_cleared | m_shifted; }public static void main(String[] args) {String n ="10000000000";BigInteger src=new BigInteger(n,2);System.out.println("n="+src.toString());String m="10011";BigInteger src2=new BigInteger(m,2);System.out.println("m="+src2.toString());int c=updateBits(1024,19,2,6);System.out.println("After updating: "+Integer.toBinaryString(c));}}
//结果n=1024m=19After updating: 10001001100
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 5.1
- 通过org.apache.commons.lang.Tokenizer解析上传的txt文件
- Java 可变参数基本用法
- linux shell if 参数
- paip.c++ 进程间通信方法大总结
- [数据结构]头插法与尾插法
- 5.1
- List的字符串容器转数组
- VC下显示JPG,BMP,GIF等图像格式(转载)
- ubuntu修改及查看mysql数据库的字符集
- iphone4 开不了机
- 合格的SEO是宏观方向与微观操作的统一
- IIS发生意外错误0x8ffe2740 大多数是80端口被其他程序占用了(Apache、迅雷)
- varchar 和varchar2 的区别
- jQuery MiniUI