数的补数 Number Complement

本文介绍了如何通过两种方法实现给定正整数的按位取反操作,即补码计算。第一种方法通过计算掩码并与原数进行位运算得到结果;第二种方法则利用了异或的性质来简化计算过程。

问题:

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.

解决:

①  注意对输入的数值转换时是32位二进制数,高位为0,不算在计算范围内,应该跳过,从第一个非0数据开始。

class Solution { // 10ms
    public int findComplement(int num) {
        int tmp = (Integer.highestOneBit(num) << 1) - 1; //00..11..1
        num = ~ num;//111...取反之后的值
        return num & tmp;//000...补码
    }
}

进化版:异或的性质---与0相^保留原值,与1相^按位取反,与自身相^结果为0.

public class Solution { // 11ms
    public int findComplement(int num) {
        int mask = (Integer.highestOneBit(num) << 1) - 1;
        return num ^ mask;
    }
}

② 利用异或的性质。

class Solution { // 11ms
    public int findComplement(int num) {
        int tmp = num;
        int count = 0;//记录非0的位数
        while(tmp != 0){
            tmp /= 2;
            count ++;
        }
        return num ^ (int)(Math.pow(2,count) - 1);
    }
}

转载于:https://my.oschina.net/liyurong/blog/1518541

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值