476. Number Complement
来源:互联网 发布:带着淘宝去异界txt 编辑:程序博客网 时间:2024/06/06 00:14
476.Number Complement
Given apositive integer, output its complement number. The complement strategy is toflip the bits of its binary representation.
Note:
The giveninteger is guaranteed to fit within the range of a 32-bit signed integer.
You couldassume no leading zero bit in the integer’s binary representation.
Example1:
Input: 5
Output: 2
Explanation:The binary representation of 5 is 101 (no leading zero bits), and itscomplement is 010. So you need to output 2.
Example2:
Input: 1
Output: 0
Explanation:The binary representation of 1 is 1 (no leading zero bits), and its complementis 0. So you need to output 0.
输出一个数各位取反之后的数。一开始没考虑直接就 return ~num;
需要注意,一个int在计算机内部是32位,如果直接取反,前面的0000会变成1111,所以在取反的时候要考虑这种情况。参考了别人的思路,很巧妙,利用mask掩码,来回取反,就出来结果了。
class Solution {public: int findComplement(int num) { unsigned mask = ~0; while(mask & num){ mask <<= 1; } return ~mask & ~num; }};
- LeetCode 476. Number Complement
- leetcode 476. Number Complement
- 【Leetcode】476. Number Complement
- 【Leetcode】476. Number Complement
- 476. Number Complement*
- LeetCode 476. Number Complement
- LeetCode 476. Number Complement
- LeetCode--476. Number Complement
- LeetCode 476. Number Complement
- 476. Number Complement
- 476. Number Complement [LeetCode]
- 476. Number Complement
- [LeetCode]476.Number Complement
- 476. Number Complement
- 【LeetCode】 476. Number Complement
- LeetCode 476. Number Complement
- 476. Number Complement
- 476. Number Complement (E)
- java中操作Oracle clob数据出现的连接关闭问题
- Java设计模式透析之 —— 模板方法(Template Method)
- 7招帮你释放Ubuntu磁盘空间
- 读/写视频文件
- Android动画
- 476. Number Complement
- 剑指offer——数组中出现次数超过一半的数字
- 归并排序
- Mybatis一级缓存原理
- C编程(五)流程控制之循环while,do while
- 【题解】 NOIP2012pj 寻宝 洛谷P1076
- DWA算法
- adb操作命令详解及大全
- 0707学习总结(类,namespace,函数重载,带默认值得函数)