476. Number Complement 难度:简单
来源:互联网 发布:淘宝自定义导航条代码 编辑:程序博客网 时间:2024/06/02 07:31
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
2. 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.
算法分析:用一个临时变量t来标记num的二进制数的长度,然后用t-1与num异或,就能得到num的补数。
C语言版
int findComplement(int num) { int n = num, t = 1; while(n) { n = n >> 1; t = t << 1; } return num ^ (t - 1);}
Python版
class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ return num ^ ((1 << num.bit_length()) - 1)
阅读全文
0 0
- 476. Number Complement 难度:简单
- LeetCode 简单操作 | 476. Number Complement
- 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
- 修改Eclipse的@author信息
- 有关||和&&以及|与||、&与&&的区别
- UVA 11178 Morley's Theorem——直线相交
- Unreal Engine 4 Scripting with C++ Cookbook
- opencv开发笔记(十三):寻找和绘制物体的凸包
- 476. Number Complement 难度:简单
- ACM-ICPC2017北京网络赛(I) Minimum
- maven标签详解
- 安卓:文字阴影
- 主成分分析(Principal components analysis)-最大方差解释
- 【知了堂学习笔记】利用js、ajax实现遍历行传参
- 【转】时钟周期,机器周期,指令周期的区别
- 3D CNN
- DeepLearing学习笔记-Sigmoid函数的梯度