简体   繁体   English

用于计算 integer 中 1 位的递归程序

[英]Recursive program for counting 1 bits in integer

I wrote an iterative program that counts of the amount of 1s in the binary of an integer given in argv[1] , my iterative version worked fine but I'm having trouble figuring out how to make the function recursive.我编写了一个迭代程序,计算argv[1]中给出的 integer 的二进制文件中 1 的数量,我的迭代版本运行良好,但我无法弄清楚如何使 function 递归。

I've tried changing the function with an if statement我尝试使用 if 语句更改 function

#include <stdio.h>
#include <stdlib.h>

int bitcount( int x ) {

  unsigned int count = 0 ;

    count += x & 1;

    x >>= 1 ;

    if ( x > 0 ) {

      bitcount( x ) ;
  }

  return count ;

}

int main( int argc, char *argv[] ) {

  int b ;

  b = atoi( argv[1] ) ;

  b = bitcount ( b ) ;

  printf( "%d\n", b ) ;

  return 0 ;

}

My iterative program gave me the correct answer, but this program will print 1 no matter what number I use.我的迭代程序给了我正确的答案,但是无论我使用什么数字,这个程序都会打印 1。

The problem is that you're not using the returned value of your bitcount function.问题是您没有使用bitcount的返回值。 Change bitcount( x );更改bitcount( x ); for count += bitcount( x );对于count += bitcount( x );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM