leetcode 比特位计数

1. 比特位计数(191)

编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count=0;
        for(;n!=0;count++){
            n=n&(n-1);
        }
        return count;
    }
}

2. 比特位计数(338)

class Solution {
    public int[] countBits(int num) {
        int[] dp = new int[num + 1];
        if(num == 0) return dp;
        dp[0] = 0;
        for(int i = 0; i <= num; i++) {
            int tmp = i;
            int sum = 0;
            while(tmp != 0) {
                sum += tmp % 2;
                tmp = tmp / 2;
            }
            dp[i] = sum;
        }
        return dp;
    }
}


class Solution {
    public int[] countBits(int num) {
        int[] dp = new int[num + 1];
        if(num == 0) return dp;
        dp[0] = 0;
        for(int i = 0; i <= num; i++) {
            dp[i] = helper(i);
        }
        return dp;
    }
    public int helper(int x) {
        int count = 0;
        for(; x != 0; count++) {
            x = x & (x - 1);
        }
        return count;
    }
}

3. 颠倒二进制数(190)

颠倒给定的 32 位无符号整数的二进制位。
示例 1:

输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。

public class Solution {
    public int reverseBits(int n) {
        int res = 0;
        for (int i = 0; i < 32; i++) {
            res = (res << 1) + (n & 1);
            n >>= 1;
        }
        return res;
    }
}
//整数反转(7)
//给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
class Solution {
    public int reverse(int x) {
        long res = 0;
        int prnot = 1;
        if(x < 0) {
            prnot = -1;
            x = -1 * x;
        }
        while(x != 0){
            res = res * 10 + x % 10;
            x /=10;
        }
        res *= prnot;
        if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE)
            return 0;
        return (int)res;
    }
}

4. 2的幂(231)

https://leetcode-cn.com/problems/power-of-two/solution/power-of-two-er-jin-zhi-ji-jian-by-jyd/

class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }
}
原文地址:https://www.cnblogs.com/aslanvon/p/13256642.html