Home > Mobile >  why does it complain integer constant is too large for its type
why does it complain integer constant is too large for its type

Time:01-15

I am writing a hamming weight calculator but why does the number 3 is too large for uint32_t ?

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

Note:

Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.

In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.

// package LeetCode Problem.Problem 2;
// Write a function that takes an unsigned integer and returns the number of '1'
// bits it has (also known as the Hamming weight).

#include <iostream>
using namespace std;

int hammingWeight(uint32_t n);

class BitShifting {
 public:
  uint32_t n;
  int hammingWeight(uint32_t n);
  void setn(uint32_t n);
};

void BitShifting::setn(uint32_t n) {
  n = n;
}

int BitShifting::hammingWeight(uint32_t n) {
  int count = 0;
  while (n) {  // while n > 0
    count  = n & 1;  // n&1 is a bit comparison for binary ends; returns 0 or 1
                     // that if true would  = 1;
    n = n >> 1;  // Shift n to the right for one bit
  }
  return count;
}

int main() {
  BitShifting n1, n2, n3;
  n1.n = 00000000000000000000000000001011;
  n2.n = 00000000000000000000000010000000;
  n3.n = 11111111111111111111111111111101;

  cout << endl
       << "The hamming weight of Input 1 is: " << n1.hammingWeight(n1.n) << endl
       << "The hamming weight of Input 2 is: " << n2.hammingWeight(n2.n) << endl
       << "The hamming weight of Input 3 is: " << n3.hammingWeight(n3.n);

  return 0;
}

CodePudding user response:

To enter literals in binary format you need to have the prefix 0b, as in 0b11111111111111111111111111111101.

For comparison, 0 is the prefix for octal numbers (011 is not even 11 decimal, it's decimal 9) and 0x is the prefix for hexadecimal numbers.

CodePudding user response:

It's because 11111111111111111111111111111101 is a decimal number.

You probably want a binary numder: 0b11111111111111111111111111111101.

In addition to that, your setn member function doesn't work. n = n assignes the local n to the local n. To assign to the member variable, either change the name of the local variable or assign it like below:

void BitShifting::setn(uint32_t n) {
  this->n = n;
}

CodePudding user response:

void BitShifting::setn(uint32_t n) {
  n = n;
}

The method argument n shadows the class member variable n. So this function does nothing. Rename the argument or the member variable.

  •  Tags:  
  • Related