求32位二进制中1的个数,这个代码不知为啥错了

public class Solution {

    // you need to treat n as an unsigned value

    public int hammingWeight(int n) {

        int count = 0;

        for(int i = 31; i >=0; i--){

            count = count + n / (1 << i);

            n = n % (1 << i);

        }

        return count;

    }

}

/* Note:Your choice is C IDE */
#include "stdio.h"
int count=0;
void tobin(int a,char* str){
  char *p=(char*)&a,c=0,f=0,pos=-1;//p指向a的首地址
  int o;
  int i;
  for(o=0;o<4;++o){
	for(i=0;i<8;++i){
      c=p[3-o]&(1<<(7-i));
      if(!f&&!(f=c))
      	continue;
      if(c){
      	count++;
      }
      str[++pos]=c?'1':'0';
    }
  }
}
void main()
{
	int a= 10000;
	char str[32]={0};
	tobin(a,str);
	printf("%s\n",str);
	
	printf("count=%d\n",count);
    
}

 

希望对你有帮助:https://blog.csdn.net/it_xiangqiang/category_10581430.html
希望对你有帮助:https://blog.csdn.net/it_xiangqiang/category_10768339.html

负数;

    public static  int  toBin(int n){
        int count = 0;
        StringBuilder sb = new StringBuilder();
        while (n !=0 ){
            if((n & 1) == 1){
                sb.append("1");
                count++;
            }else{
                sb.append("0");
            }
             n >>>= 1;
        }
        System.out.println(sb.reverse());
        System.out.println(count);
        return count;
    }

 

    public static int bitCount(int n) {
        int count = 0;
        while (n != 0) {
            count += n & 1;//最后一位与1运算n=7(111) 111&001=1
            n >>>= 1;//将最后一位位移出 111>>>1=011
        }
        return count;
    }

 

没看出问题,你是哪个测试用例没通过呢?不过这个汉明距离一般用 每次 n & (n-1)来去掉1的方法来解吧,你这个有点慢吧

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632

非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!

速戳参与调研>>>https://t.csdnimg.cn/Kf0y