首页 > 其他分享 >计算位1的个数方法总结

计算位1的个数方法总结

时间:2023-01-22 10:02:14浏览次数:48  
标签:总结 tmp return int 个数 while 计算 ans diff



tags: DSA C++ Python

写在前面

之前介绍过一种计算整数二进制表示中位​​1​​个数的文章, 是介绍通过不断减去右移一位之后的值的方法来完成的, 后来发现还有一种更快更经典的方法, 下面来总结下.

​191. 位1的个数 - 力扣(LeetCode)​​;

各种思路

转换字符串

def calcbit1_v1(n):
return bin(n).count("1")
# return n.bit_count()

取最低位

def calcbit1_v2(n):
ans = 0
while n:
tmp = n & 1 # 取最末位
ans += tmp
n >>= 1 # 进位
return ans
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans{};
while (n) ans += (n & 1), n >>= 1;
return ans;
}
};

加减法

def calcbit1_v3(n):
total = 0
tmp = n
while tmp:
tmp >>= 1
total += tmp
return n - total


def calcbit1_v4(n):
diff = n
while n:
n >>= 1
diff -= n
return diff

之前介绍过, 比较超出常规的方法.

class Solution {
public:
int hammingWeight(uint32_t n) {
auto diff{n};
while (n) n >>= 1, diff -= n;
return diff;
}
};

另一种取最低位的方法

class Solution {
public:
int hammingWeight(uint32_t n) {
int ans{};
while (n) n &= n - 1, ++ans;
return ans;
}
};

最经典的位运算

​​统计二进制展开中数位1的个数的优化 - Maples7 - 博客园 (cnblogs.com)​​;

分组计算


计算位1的个数方法总结_Python

class Solution {
public:
int hammingWeight(uint32_t n) {
n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f);
n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff);
n = (n & 0x0000ffff) + ((n >> 16) & 0x0000ffff);
return n;
}
};


标签:总结,tmp,return,int,个数,while,计算,ans,diff
From: https://blog.51cto.com/u_15366127/6021430

相关文章

  • putty使用教程(总结)
    putty使用教程(总结):https://www.cnblogs.com/yuwentao/archive/2013/01/06/2846953.html最近开始使用putty,在网络上看到一份很不错的教程,共享一下:putty使用方法,中文教程......
  • 【博学谷学习记录】超强总结,用心分享 | 文字爬虫
    【博学谷IT技术支持】目的:抓取网站文字一、使用到的python库requests库//安装pipinstallrequests//导入importrequests//headerheaders={'user-agent......
  • 第三周总结报告
    第三周总结报告SMUWinter2023Round#5(Div.2)总结:本次模拟赛本来是在洛谷举行,但因为有bug换到了codeforces上,本场比赛我做出来了A,B,C,D四道题,......
  • c++中运算符重载总结
    运算符重载的本质是函数重载。语法格式重载函数的一般格式如下:返值类型operator运算符名称(形参表列){    重载实体;}operator运算符名称在一起构成了新的函......
  • 类内const与static修饰符总结
    const用处常数据成员const修饰类的成员变量,表示成员常量,不能被修改,同时它只能在初始化列表中赋值(c11中支持类中实始化)。可被const和非const成员函数调用,而不可以修改......
  • 程序:用递归法计算字符串长度
    #include<stdio.h>intmy_strlen(char*str){if(*str!='\0')return1+my_strlen(str+1);elsereturn0;}intmain(){intret=0;chararr[]="hibi......
  • 程序:运用函数交换两个数据
    注意:是传送地址,才能改变原数据!!!#include<stdio.h>voidswap(int*pa,int*pb){intz=0;z=*pa;*pa=*pb;*pb=z;return0;}intmain(){inta=210;int......
  • 程序:计算10个数字中最大的一个
    #include<stdio.h>intmain(){intarr[]={1,3,4,5,7,8,9,10,12,2};intmax=arr[0];intleft=0;intright=sizeof(arr)/sizeof(arr[0]);for(left=0;......
  • 程序:计算1/1-1/2+1/3......-1/100
    #include<stdio.h>intmain(){inti=1;intflag=1;doublesum=0;for(i=1;i<=100;i++){sum+=flag*(1.0/i);flag=-flag;}prin......
  • 程序:运用函数找出100至200的素数,并数出个数
    #include<stdio.h>intif_a_is_prime(intd){intc=2;for(c=2;c<d;c++){if(d%c==0){return0;}}return1;}intmain(){inta=......