5.1 You are given two 32-bit numbers, N andM, and two bit positions, i and j. Write a method to insert M into Nsuch 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 ofM. That is, ifM= 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.

update某一位的时候,记得要把该位清零先。

Method 1: mask = ~((1<<(i-j+1)-1)<<i)

Method 2:mask=(~0<<(j+1)) | ((1<<i) - 1)

5.2 Given a real number between 0 and 7 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR."

小数的表示啊。用除法得到的是reverse的串。用乘法可以得到正串。

5.3 Given a positive integer, print the next smallest and the next largest number that have the same number of 7 bits in their binary representation.

用位操作方法很直观,用算术方法比较巧妙一些。arithmetically。

getNext: n + (1 << c0) + (1 << (c1-1)) - 1;

getPrev: n - (1 << c1) - (1 << (c0-1)) + 1;

5.4 Explain what the following code does: ((n & (n-1)) == 0).

check一下n是不是2的k次方。

也可以用来检验二进制中1的个数。

5.5 Write a function to determine the number of bits required to convert integer A to integer B.

就是用n&(n-1)来计算。这个操作每次可以把least significant bit为1的给清零。

5.6 Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit! are swapped, bit 2 and bit 3 are swapped, and so on)

巧妙。移偶数位,移奇数位。

5.7 An array A contains all the integers from 0 through n, except for one number which is missing. In this problem, we cannot access an entire integer in A with a single operation. The elements of A are represented in binary, and the only operation we can use to access them is "fetch thejth bit ofAfi]," which takes constant time. Write code to find the missing integer. Can you do it in 0(n) time?

最简单的做法就是累加0到n,用求和公式得到的和减去计算出来的和,得到missing number。复杂度是O(nlgn)。因为n有lgn+1个bit。其实lgn一般也就32,如果n>>32,当然这种算法还是可以的。

所以还是要二分,想到了要按位计数,但是没有想到比较0的个数和1的个数。

在确定了LSBi的值后,需要去掉那些不符合的结果。

5.8 A monochrome screen is stored as a single array of bytes, allowing eight consecutive pixels to be stored in one byte. The screen has width w, where w is divisible by 8 (that is, no byte will be split across rows). The height of the screen, of course, can be derived from the length of the array and the width. Implement a function drawHorizontalLine(byte[] screen, int width, intxl, intx2, inty) which draws a horizontal line from (x 1, y) to (x2, y).

 string binary(int n) {
stringstream s; //while (n) { // negative number will always refill 1s for the most significant digit
for (int i = ; i < ; ++i) {
s << (char)('' + (n & 0x01));
//cout << (char)('0' + (n & 0x01)) << endl;
//cout << n << endl;
n = n >> ;
}
string ret = s.str();
int i = , j = ret.length() - ;
while (j > i) {
swap(ret[i], ret[j]);
i++; j--;
}
return ret;
} // 5.3
int getNextSmallest(int n) {
int i = , c1 = ;
for (; i <= && (n & ( << i)) == ; ++i);
for (; (n & ( << i)) != ; ++i, ++c1);
if (i > ) return -;
n |= << i; // set i-th bit
n &= ~ << i;
n |= (( << (c1 - )) - );
return n;
} int getPrevLargest(int n) {
// example: 11100111
int i = , c1 = ;
for (; (n & ( << i)) != ; ++i, ++c1); // ignore 1s, c1=3
for (; i <= && (n & ( << i)) == ; ++i); // find first 1, i=5
if (i > ) return -; // error, 00001111
n &= ~ << (i + ); // clear i-th bit, n=11000000
n |= (( << (c1 + )) - ) << (i - c1 - ); //n=11011110
return n;
} // 5.5
int diffBits(int a, int b) {
int count = ;
for (int n = a ^ b; n != ; n = n & (n - )) {
count++;
}
return count;
} // 5.6
int swapBits(int n) {
int ret = ;
for (int i = ; i < ; i += ) {
int tmp = (n >> i) & 0x03;
switch (tmp) {
case : ret |= ( << i); break;
case : ret |= ( << i); break;
case : ret |= ( << i); break;
}
}
return ret;
} int swapBits2(int n) {
return ((n & 0xaaaaaaaa) >> ) | ((n & 0x55555555) << );
} // 5.8
void drawLine(char* screen, int width, int x1, int x2, int y) {
int p1 = y * width + x1, p2 = y * width + x2;
int b1 = p1 >> , b2 = p2 >> ; //bucket
int s1 = p1 & 0x07, s2 = p1 & 0x07; //shift
for (int i = b1 + ; i < b2; ++i) {
screen[i] = 0xff;
}
int m1 = 0xff >> s1, m2 = ~(0xff >> (s2 + )); //mask
if (b1 == b2) {
screen[b1] |= (m1 & m2);
} else {
screen[b1] |= m1;
screen[b2] |= m2;
}
}

Careercup | Chapter 5的更多相关文章

  1. Careercup | Chapter 1

    1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot us ...

  2. Careercup | Chapter 3

    3.1 Describe how you could use a single array to implement three stacks. Flexible Divisions的方案,当某个栈满 ...

  3. Careercup | Chapter 2

    链表的题里面,快慢指针.双指针用得很多. 2.1 Write code to remove duplicates from an unsorted linked list.FOLLOW UPHow w ...

  4. Careercup | Chapter 8

    8.2 Imagine you have a call center with three levels of employees: respondent, manager, and director ...

  5. Careercup | Chapter 7

    7.4 Write methods to implement the multiply, subtract, and divide operations for integers. Use only ...

  6. CareerCup Chapter 9 Sorting and Searching

    9.1 You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B. ...

  7. CareerCup chapter 1 Arrays and Strings

    1.Implement an algorithm to determine if a string has all unique characters What if you can not use ...

  8. CareerCup Chapter 4 Trees and Graphs

    struct TreeNode{ int val; TreeNode* left; TreeNode* right; TreeNode(int val):val(val),left(NULL),rig ...

  9. Careercup | Chapter 6

    6.2 There is an 8x8 chess board in which two diagonally opposite corners have been cut off. You are ...

随机推荐

  1. python爬虫基础17-抓包工具使用

    01 抓包工具原理 HTTP 由于HTTP请求是没有加密的,也没有做任何验证,所以抓包工具直接将请求转发即可. HTTPS 由于HTTPS请求,客户端会使用服务端的证书来加密数据,而且会验证服务端是否 ...

  2. Can Japan stand up to US request to contain China?

    From Global Times Two days before US President Donald Trump's visit to Japan, A fake news story caug ...

  3. 用Python抓取并分析了1982场英雄联盟数据,教你开局前预测游戏对局胜负!

    英雄联盟想必大多数读者不会陌生,这是一款来自拳头,由腾讯代理的大型网络游戏,现在一进网吧,你就能发现一大片玩英雄联盟的人.在2017年中国战队无缘鸟巢的世界总决赛后,一大片人选择了弃游,只是终究没躲过 ...

  4. debian安装之后使用android手机上网

    安装debian的过程中,没有连接网线.因为路由器在客厅,电脑在卧室,拖条长长的线很不方便. 断网安装完成之后,通过usb连上i9250. 在i9250上,执行以下操作: “设置”--->“更多 ...

  5. Pycharm Django开发(一)设置开发环境

    一 由于我是一个对开发环境有强迫症的人,在装完PYTHON 2.6 3.3  3.4中,在创建Django工程的时候,会出现N个版本的python,那么在这里可以设置你喜欢和要使用的版本.

  6. Hydux: 一个 Elm-like 的 全功能的 Redux 替代品

    在学习和使用 Fable + Elmish 一段时间之后,对 Elm 架构有了更具体的了解, 和预料中的一样,Redux 这种来自 Elm 的风格果然还是和强类型的 Meta Language 语言更 ...

  7. python 学习分享-基础篇

    1.python起手式 写下第一个代码,打印‘hello world’ print('hello world') 2.变量 变量是为了存储信息,在程序中被调用,标识数据名称或类型. 变量定义的规则: ...

  8. Verlet Integration

        Verlet Integration Verlet 积分法是一种用于求解牛顿运动方程的数值方法,被广泛运用于动力学模拟以及视频游戏中.尔莱算法的优点在于:数值稳定性比简单的欧拉方法高很多,并保 ...

  9. [UiAutomator篇][3] 打开音乐应用的测试脚本

    package qq.test; import android.content.Context; import android.content.Intent; import android.suppo ...

  10. 设计模式(十六)迭代器模式 Iterator

    什么时候需要用到迭代器模式? 有许多中方法,可以把对象堆起来放进一个集合(可以是数组.堆栈.列表.哈希表,等等). 每一种类型的集合,都有各自适用的时机.但是某个时间段,客户端可能希望去遍历这个集合. ...