博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Number Complement 补数
阅读量:7061 次
发布时间:2019-06-28

本文共 1556 字,大约阅读时间需要 5 分钟。

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: 5Output: 2Explanation: 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: 1Output: 0Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

这道题给了我们一个数,让我们求补数。通过分析题目汇总的例子,我们知道需要做的就是每个位翻转一下就行了,但是翻转的起始位置上从最高位的1开始的,前面的0是不能被翻转的,所以我们从高往低遍历,如果遇到第一个1了后,我们的flag就赋值为true,然后就可以进行翻转了,翻转的方法就是对应位异或一个1即可,参见代码如下:

解法一:

class Solution {public:    int findComplement(int num) {        bool start = false;        for (int i = 31; i >= 0; --i) {            if (num & (1 << i)) start = true;            if (start) num ^= (1 << i);        }        return num;    }};

由于位操作里面的取反符号~本身就可以翻转位,但是如果直接对num取反的话就是每一位都翻转了,而最高位1之前的0是不能翻转的,所以我们只要用一个mask来标记最高位1前面的所有0的位置,然后对mask取反后,与上对num取反的结果即可,参见代码如下:

解法二:

class Solution {public:    int findComplement(int num) {        int mask = INT_MAX;        while (mask & num) mask <<= 1;        return ~mask & ~num;    }};

再来看一种迭代的写法,一行搞定碉堡了,思路就是每次都右移一位,并根据最低位的值先进行翻转,如果当前值小于等于1了,就不用再调用递归函数了,参见代码如下:

解法三:

class Solution {public:    int findComplement(int num) {        return (1 - num % 2) + 2 * (num <= 1 ? 0 : findComplement(num / 2));    }};

 本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。

你可能感兴趣的文章
php 依赖注入容器
查看>>
算法笔记_130:行列递增矩阵的查找(Java)
查看>>
HDU 1418 抱歉 (欧拉公式)
查看>>
C#上位机串口控制12864显示
查看>>
自动化测试
查看>>
postgresSQL 实现数据修改后,自动更新updated_date/ts等字段
查看>>
老黄历接口(免注册)
查看>>
移动端开发适配总结
查看>>
CSS3阴影 box-shadow的使用和技巧总结
查看>>
RAC下修改SGA的实战操作
查看>>
JQuery/AjaX/Javascript/DIV+CSS资源下载地址
查看>>
linux下使用lftp的小结
查看>>
jqGrid的若干种用法
查看>>
jQuery实现文本框回车键转tab键 分类: JavaScript ...
查看>>
内存程序文件、内存对齐程序
查看>>
wp7设置浏览器主页
查看>>
资源管理更新系统V2.0版的一些问题
查看>>
Sil“.NET研究”verlight与HTML双向交互
查看>>
More-iOS中的Ping
查看>>
React 重要的一次重构:认识异步渲染架构 Fiber
查看>>