LeetCode :Number Complement

来源:互联网 发布:网络优化工程师培训费 编辑:程序博客网 时间:2024/06/07 18:52

2017年2月27日      星期一

   经历了一个浑浑噩噩的周末,终于到了星期一。昨天还去了中国美术学院(象山校区),可以说是被艺术的氛围熏陶了一下!去过的艺术院校里,四川美术学院给我的感觉,既有过往的建筑风格,又有很现代的建筑,大家都不拘泥于形式;而中国美术学院,十分学术派,可以说把中国古代的结构、工艺发挥的淋漓尽致。很羡慕他们能在这样的地方学习!

    好啦,开始今天的题目:

      Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.

------------------------------------------------------------我是分割线------------------------------------------------------------------

由题目可知:对一个数二进制取反,输出取反后的整数。同样可以通过位运算的方式计算。

                        在存储过程中,一个整数前面可能会有n个0,不能直接通过~取反。所以方案就是从左到右找到的第一位1,开始与1异或

                        代码如下:

class Solution {public:    int findComplement(int num) {        bool start = false;        for (int i = 31; i >= 0; --i) {            if (num & (1 << i)) start = true;            if (start) num ^= (1 << i);        }        return num;    }};



0 0