LEETCODE--Number Complement
来源:互联网 发布:南京seo 编辑:程序博客网 时间:2024/05/16 17:16
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.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
方法一:
刚开始没有好的想法就只好利
异或运算的性质:
使特定位翻转 找一个数,对应X要翻转的各位,该数的对应位为1,其余位为零,此数与X对应位异或即可。
例:X=10101110,使X低4位翻转,用X ^ 0000 1111 = 1010 0001即可。
使相反传的位置范围与相对应范围的全1(1……1)进行异或运算即可得到complement number;
以这个思想的难点就是找到相应的全1数;
法二:
二进制按位计算技巧
class Solution {public: int findComplement(int num) { unsigned x = ~0; while(x & num) x <<= 1; return ~x & ~num; }};
- LeetCode 476. Number Complement
- leetcode 476. Number Complement
- [leetcode-476]Number Complement
- LeetCode Number Complement
- leetcode-476- Number Complement
- 【Leetcode】476. Number Complement
- 【Leetcode】476. Number Complement
- LeetCode 476. Number Complement
- LEETCODE--Number Complement
- LeetCode 476. Number Complement
- LeetCode--476. Number Complement
- LeetCode 476. Number Complement
- leetcode 476 Number Complement
- 476. Number Complement [LeetCode]
- [LeetCode]476.Number Complement
- LeetCode题解: Number Complement
- 【LeetCode】 476. Number Complement
- LeetCode 476. Number Complement
- HTTP协议之multipart/form-data请求分析
- 分布式集群Session共享 简单多tomcat8+redis的session共享实现
- JS - 作用域和上下文环境
- Unity3D占用内存太大的解决方法
- Masonry适配——(6)登录视图示例
- LEETCODE--Number Complement
- IOS ARC下内存泄露总结
- Android基站定位——通过手机信号获取基站信息(一)
- 《企业云桌面实施》-小技巧-01-规划注意事项
- DOM 元素
- linux多线程之条件变量
- Minimum Path Sum
- java代码发送邮件,并携带附件
- POJ-3481 Double Queue,Treap树和set花式水过!