版权声明:此文章为许诗宇所写,如需转载,请写下转载文章的地址 https://blog.csdn.net/xushiyu1996818/article/details/83141761
题目及测试
package pid191;
/*位1的个数
编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
示例 :
输入: 11
输出: 3
解释: 整数 11 的二进制表示为 00000000000000000000000000001011
示例 2:
输入: 128
输出: 1
解释: 整数 128 的二进制表示为 00000000000000000000000010000000
*/
public class main {
public static void main(String[] args) {
int[] testTable = new int[]{11,128,63,2147483647};
for (int ito : testTable) {
test(ito);
}
}
private static void test(int ito) {
Solution solution = new Solution();
int rtn;
long begin = System.currentTimeMillis();
System.out.print("ito="+ito+" ");
System.out.println();
//开始时打印数组
rtn = solution.hammingWeight(ito);//执行程序
long end = System.currentTimeMillis();
//System.out.println(ito + ": rtn=" + rtn);
System.out.println( " rtn=" +rtn);
// for (int i = 0; i < ito.length; i++) {
// System.out.print(ito[i]+" ");
// }//打印结果几数组
System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}
}
解法1(失败)
输入: 2147483648 (10000000000000000000000000000000)
超出int范围,不知道怎么办
使用位运算
与1与运算,为1为奇数,为0位偶数
之后n>>2,相当于/2
package pid191;
class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
if(n<=0){
return 0;
}
int result=0;
while(n!=0){
if((n&1)==1){
result++;
n=n>>1;
}
else{
n=n>>1;
}
}
return result;
}
}
解法2(成功,4ms,较慢)
将
if(n<=0){
return 0;
}
去除,因为要处理负数
同时,将>>改为>>>因为>>如果全为1(也就是-1)的话0不会填位,而>>>会
public int hammingWeight(int n) {
int result=0;
while(n!=0){
if((n&1)==1){
result++;
n=n>>>1;
}
else{
n=n>>>1;
}
System.out.println(n);
}
return result;
}
解法3(别人的)
做了优化,直接+(n&1)
public class Solution
{ // you need to treat n as an unsigned value public int hammingWeight(int n)
{ int sum = 0;
while(n != 0)
{ sum += (n & 1);
n >>>= 1;
}
return sum; } }