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.
idea: we only want to flip the lower k bits (k is the bits number of num)
Solution 1: use mask to find the leftmost 1 of num, and then use ~mask to make only the k lowest bits to be 1(k is the bits number of num), and then & ~num to get the result.
class Solution { public: int findComplement(int num) { unsigned mask=INT_MAX; while((mask&num)!=0){ mask= mask << 1; } return (~mask & ~num); } };
Solution 2: the needed mask is (2^(int)log(num))-1=(1<<(int)log(num))-1
class Solution { public: int findComplement(int num) { return ~num & ((1 <<(int)log2(num))-1); } };
开源WebOS
公交车路线查询系统后台数据库设计
网页信息抓取
一步一步打造WebIM(3)——性能测试
WebBrowser介绍——Javascript与C++互操作
.NET文档生成工具ADB[更新至2.3]
一步一步打造WebIM(4)——Comet的特殊之处
在SQL Server中对视图进行增删改
开源企业即时通讯和在线客服
- 最新文章
-
招聘产品经理&系统分析师
Shanghai MCT Technology 招聘软件开发项目经理/系统架构师/.Net高级开发工程师
C#如何在Form中嵌入并且操作Excel表格
招聘.Net系统架构师
解决event.layerX and event.layerY are broken and deprecated in WebKit的问题
live()解决Jquery采用append添加的元素事件无效和获取不到添加元素的值
新申请的博客
uImage烧写中出现“Loading: T T T T T T T T T T T T T T T T T T T T”时解决方法
Linux下C语言的文本文件读写(fputc,fgetc,fwrite,fread对文件读写操作)
linux下vi编辑器常用命令