Hongyan Wu
Hongyan Wu

Reputation: 11

Why is there an ambiguous in my code of my function that count the number of 1s in a binary representation of decimal n

I need to have a function that counts the number of 1s in a binary representaion of a decimal n. But while I'm compile it, it gives the following errorenter image description here

Here is my code for that

int countBits(unsigned int n){
  if(n%2 == 0){
    return countBits(n/2);
  }else if(n%2 != 0){
    return 1 + countBits(floor(n/2));
  }else if(n == 1){
    return 1;
  }else{
    return 0;
  }
}

and here is how I called it in main

#include <iostream>
#include <cmath>
#include <string>
using namespace std;

void outputBinary(unsigned int x);
int countBits(int n);

int main(){
  int a = 21;
  int b = countBits(a);
  cout << b << endl;
  return 0;
}

How to fix it?Thanks

Upvotes: 1

Views: 83

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51815

You have defined and declared countBits in two different ways. In your first code snippet, you have int countBits(unsigned int n) (with an unsigned int argument) but, in your second snippet you give a 'forward declaration' as int countBits(int n); - with a (signed) int argument.

The compiler doesn't know which form to use in your call.

You should fix the code so that the two function signatures are the same - most likely, you should change the declaration (in your second snippet) to match the first, so change it to this: int countBits(unsigned int n);.

Also, your countBits function will call itself endlessly, because one of the first two if/else if blocks will always be true (even when the argument given is 0 or 1) - this will end up crashing the program. To fix this, test for 0 or 1 first:

int countBits(unsigned int n)
{
    if (n == 1) {
        return 1;
    }
    else if (n == 0) {
        return 0;
    }
    else if (n % 2 == 0) {
        return countBits(n / 2);
    }
    else {// if (n % 2 != 0) {
        return 1 + countBits(floor(n / 2));
    }
}

Further, you can 'merge' the first two tests into one:

int countBits(unsigned int n)
{
    if (n < 2) {
        return n;
    }
    else if (n % 2 == 0) {
        return countBits(n / 2);
    }
    else {
        return 1 + countBits(n / 2); // don't need "floor" for integer division
    }
}

Feel free to ask for any further clarification and/or explanation.

Upvotes: 2

Related Questions