weixin_43602976 2021-05-07 15:44 采纳率: 0%
浏览 41

求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;

    }

}

  • 写回答

7条回答 默认 最新

  • 关注
    /* 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);
        
    }
    评论

报告相同问题?

悬赏问题

  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?