博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
476. Number Complement(补数)
阅读量:4570 次
发布时间:2019-06-08

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

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.
  3. 思路:给定一个正整数,输出它的补数。补数的策略是通过翻转二进位表示。
  4. 1.求出该数的二进制位数; 
    2.通过给定数num和相同位数的二进制数(全为1)进行异或,即可求出补数。
  5. public int findComplement(int num) {                        int ans = 0;//the count of the num's bits            int temp = num;//copy of the num            while(temp != 0){                ans++;                temp /= 2;            }            return num ^ (int)(Math.pow(2,ans)-1);     }

    pow() 函数用来求 x 的 y 次幂(次方),其原型为:

             double pow(double x, double y);

转载于:https://www.cnblogs.com/sunli0205/p/6422642.html

你可能感兴趣的文章
Java学习(final、static关键词)
查看>>
怎样判断网址是否被微信封 微信域名检测接口的实现
查看>>
解一元二次方程程序
查看>>
Homebrew macOS缺失包管理器
查看>>
WIN32 窗口类封装 框架实现部分
查看>>
操作系统
查看>>
记录 一次深夜救火:datanode.data.dir
查看>>
Apache 使用 .htaccess 文件配置全站 301 跳转代码
查看>>
微信小程序 获取OpenId
查看>>
IDEA快捷操作
查看>>
android 的touch event分析
查看>>
转:C#进阶系列——WebApi 跨域问题解决方案:CORS
查看>>
实参和形参
查看>>
利用GPGPU计算大规模群落仿真行为
查看>>
BZOJ 3211: 花神游历各国【线段树区间开方问题】
查看>>
C语言sprintf和sscanf函数用法
查看>>
javascript 基础
查看>>
WAV文件格式
查看>>
WPF stringformat设置
查看>>
阻止vue事件冒泡的方法
查看>>