博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
整数的二进制表达式中有多少个1
阅读量:4171 次
发布时间:2019-05-26

本文共 909 字,大约阅读时间需要 3 分钟。

题目:

给定一个32位整数n,可为0,可为正,也可为负,返回该整数二进制表达中1的个数

解法:

一、最简单的解法

整数n每次进行无符号右移一位,检查最右边的bit是否为1来进行统计,代码如下:

public int count1(int n){    int res=0;    while(n!=0){        res+=n&1;        n>>>=1;    }    return res;}

上面这个方法在最复杂的情况下要经过32次循环

二、下面看一个循环次数只与1的个数有关的解法。

public int count2(int n){    int res=0;    while(n!=0){        n&=(n-1);        res++;    }    return res;}

三、与count2方法复杂度一样的是如下代码中的count3方法:

public int count3(int n){    int res=0;    while(n!=0){        n-=n&(~n+1);        res++;    }    return res;}

每次进行n-=n&(~n+1)操作的时候,是移除最右侧的1的过程,等号右边n&(~n+1)的含义是得到n中最右侧的1,这个操作在位运算的题目中常出现。例如:n=01000100,n&(~n+1)=00000100,n-n&(~n+1)=01000000。

四、一种看起来很“超自然”的解法,平行算法

public int count4(int 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);}

参考自:《程序员代码面试指南》

转载地址:http://zryai.baihongyu.com/

你可能感兴趣的文章
看一个大男人是怎样处理家庭矛盾的(绝对经典)(转)
查看>>
VMware6辅助启动.bat
查看>>
升级linux内核到2.6.24
查看>>
vbs脚本大全,配有实例
查看>>
WIN32汇编基础
查看>>
Win32汇编基础教程
查看>>
“VM6辅助启动.bat”生成器.hta
查看>>
windows脚本调试howto
查看>>
五笔86版字根图程序
查看>>
Oracle EBS R12 - Use Rman to Clone Oracle EBS R12.1.1 without shutting down source Database and MT
查看>>
Oracle EBS - What happening when executing adpreclone.pl in DB and Apps Tier?
查看>>
Oracle EBS - What happening when executing adcfgclone.pl in DB Tier as well as Apps Tier?
查看>>
Oracle EBS - Details of Adpreclone and Adcfgclone
查看>>
两个对Oracle性能影响很大的io参数
查看>>
Win32ASM备忘之搭建UltraEdit实验环境
查看>>
The Best Linux Distribution of them all
查看>>
Oracle Apps DBA Interview Questions
查看>>
简单屏幕锁(Simple Screen Locker) 1.1.6.16
查看>>
Bash String Manipulation Examples – Length, Substring, Find and Replace
查看>>
String Operations in Shell
查看>>