【CS61C】Lab2 实验解析

前言
本人学习的是 2020 fall版的CS61C,本文将对Lab2解题思路做大致介绍,具体代码可以参考我的仓库
解题思路
Exercise 1: Bit Operations
三道位运算的题目中值得一说的是第二道,函数接口如下
1 | // Set the nth bit of the value of x to v. |
题目限制如下
You may ONLY use bitwise operations such as and (&), or (|), xor (^), not (~), left shifts («), and right shifts (»). You may not use any for/while loops or conditional statements. You also may not use modulo (%), division, addition subtraction, or multiplication for this question.
我的解题思路是:
- 首先分析只有当需要变化的位和不同时才会发生改变。
- 需要通过位运算找到位反转的方式和判断不同的方式
- 位反转:通过异或实现
- 判断不同: 通过移位到最低位比较得到
具体代码如下
1 | void set_bit(unsigned * x, unsigned n, unsigned v) { |