476. Number Complement(C语言)

本文介绍了一种求解整数二进制补数的方法,通过位运算实现对给定正整数二进制表示的每一位进行翻转,并提供了一个具体的C语言实现示例。

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 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.
提意:

给一个[-1000,1000]区间内的数,对它二进制的数求反然后输出

思路:

输入:num

求反:因为是二进制的操作,所以就想到什么位运算(^)、与运算(&)、左移(<<)右移(>>)这些东西

   举例子101取反就是010110取反就是001,100取反就是011

  位运算的规则是相同的取0,不同的取1

          那么101111进行位运算得出的就是010,110111的结果是001,100111位运算的结果就是011

          下一步就是想怎么找到和num位数相同的111

  看了眼答案,discuss给出的结果就是for(i=1;i<=num;i*=2)     num^=i;

  也就是说,在i=1,2,4,8,16,32....的时候 循环和num进行位运算,也就是i=1,10,100,1000,1000

          很好,正好可以和num的位数相同,只不过是一位一位的进行位运算

输出:num

int findComplement(int num) {
    //int num=0;
    long i=1;
    for(i=1;i<=num;i*=2){
        num^=i;
    }
    return num;
}
tips:

1.因为num有正有负,所以i变成long型

2.for(i=1;i<=num;i*=2) 里面的i*=2不能写成i*2....我也不知道为什么


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值