【leetcode】【套路题】476. Number Complement
一、题目描述
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.
思路:这种题没什么办法,记住这个套路吧。举个例子,num = 00000101时,另mask = ~0 = 11111111,让mask变为 11111000,然后计算~mask & ~num即可得到结果
代码:
class Solution {
public:int findComplement(int num) {unsigned mask = ~0;while(mask & num){mask = mask << 1;}return ~mask & ~num;}
};
【leetcode】【套路题】476. Number Complement相关推荐
- 263.Ugly Number||202 happy number||476 Number Complement||136 Single Number
263.Ugly Number 判断因数是否只有素数2.3.5.. 感觉比较简单: class Solution(object):def isUgly(self, num):""& ...
- Leetcode 476. Number Complement 补数 解题报告
1 解题思想 这道题给了一个正的整数,然后需要计算一个特殊的补数,这个补数的计算方式是: 1.对于这个整数num,转换成对应的二进制表示,这个二进制表示共有x位(不高于32) 2.将这x位取反后,得到 ...
- leetcode 476. Number Complement | 476. 数字的补数(位运算)
题目 https://leetcode.com/problems/number-complement/ 题解 class Solution {public int findComplement(int ...
- LeetCode 476. Number Complement
题目: Given a positive integer, output its complement number. The complement strategy is to flip the b ...
- leetcode算法题--Minimum Number of Arrows to Burst Balloons
原题链接:https://leetcode.com/problems/queue-reconstruction-by-height/ bool cmp(vector<int> a, vec ...
- 476 Number Complement
问题:给定一个整数,返回它的补数.补数的是将原数据的二进制表示反转.例如 5 的二进制位是 101,反转之后是:010,也就是整数2.所以输入5,返回2..输入1,返回0. 思路:取反操作是~,例如~ ...
- LeetCode第九题—— Palindrome Number(判断回文数)
题目描述 Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same ...
- Leetcode算法题-解法转载
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/fuxuemingzhu/article/details/85112591 作者: 负雪明烛 i ...
- LeetCode算法题-Number Complement(Java实现-五种解法)
这是悦乐书的第240次更新,第253篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第107题(顺位题号是476).给定正整数,输出其补码数.补充策略是翻转其二进制表示的位 ...
最新文章
- iOS 远程通知(Remote Notification)和本地通知(Local Notification)
- 64位Ubuntu kylin 16.04安装wine QQ
- 如何使用功能性JavaScript编写经典游戏Snake并在浏览器中播放-完整的代码示例教程
- Lateral View使用指南
- 动态的给python添加进度条_python动态进度条的实现代码
- Data Guard组件等相关介绍
- Python基础——使用with结构打开多个文件
- 小数据池.深浅拷贝.集合
- Braid,另类游戏
- 微信小程序订阅消息,并跳转指定页面
- scrapy 架构文档
- 以图搜图 图像匹配_基于内容的图像检索(CBIR) ——以图搜图
- SQL Server 函数汉字转首字母或全拼
- 瑞幸的野望,小鹿茶的突袭
- read/write 阻塞/非阻塞
- python switch函数
- 无线视频监控系统设计
- 国际快递清关要多少时间,国际快递进口如何清关2021.12.01
- 静默活体检测之Silent-Face-Anti-Spoofing
- CSS库 Tailwind