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;
}
}
未经作者同意请勿转载
本文来自博客园作者:aixueforever,原文链接:https://www.cnblogs.com/aslanvon/p/13256642.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)