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 (no leading zero bits), and its complement is . 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.
 public class Solution {
public int findComplement(int num) {
int mask = (Integer.highestOneBit(num) << 1) - 1;
num = ~num;
return num & mask;
}
}
Integer.highestOneBit(num); //01101返回1000,001返回1,101返回100

为什么需要mask:

例如num = 0000 1010,那么 ~num = 1111 0101,加入mask = 0000 1111后,~num前面的1都消除了。

最新文章

  1. mac下安装mysql教程
  2. 一款简洁大气的jquery日期日历插件
  3. NGUI 使用EventDelegate.Add与UIInput.onSubmit、UIInput.onChange限定编辑框中的内容
  4. 利用反射实现类通用的DAO层
  5. MAC电脑操作快捷键
  6. Less/Sass编译工具,koala使用指南
  7. 通知栏Notification的学习
  8. 用Get-ADComputer取非常用属性的值
  9. 初识 Asp.Net内置对象之Cookie对象
  10. 低压差稳压器AMS1585
  11. UVa 10020 - Minimal coverage(区间覆盖并贪心)
  12. java提高篇(五)-----使用序列化实现对象的拷贝
  13. HDU 4329 MAP(stringstream的用法)
  14. leetcode day8
  15. When Startup Disk is Full
  16. oldboy s21day15模块装饰器及其他应用
  17. 跨源资源共享(CORS)概念、实现(用Spring)、起源介绍
  18. 【题解】 bzoj3894: 文理分科 (网络流/最小割)
  19. java重新学习记载的一些资料。
  20. Snip for Mac(桌面截图工具)安装

热门文章

  1. SDUT OJ 数据结构实验之二叉树八:(中序后序)求二叉树的深度
  2. linux下配置apache多站点访问-小案例
  3. C++_异常1-调用abort()
  4. java的Spring学习2- junit和mock
  5. dedecms 中变量函数
  6. [转] CSS 选择器参考手册
  7. vue 调用常量的config.js文件
  8. TT 安装 之 AIX
  9. window.open打开窗口的几种方式
  10. http statusCode(状态码) 200、300、400、500序列详解