LeetCode: 476. Number Complement

来源:互联网 发布:js贪吃蛇 编辑:程序博客网 时间:2024/06/03 20:05

LeetCode: 476. Number Complement

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
1. 32-bit signed integer. You could assume no leading zero bit in the
2. integer’s binary representation.

public class Solution {    public int findComplement(int num) {        int length = (int) (Math.log(num) / Math.log(2)) + 1;        int mod = ~(0xffffffff << length);        return (~ num) & mod;    }}