-2

Hello I need some help I don't have any idea of how to do it this sorry for my english

I need to do a program in C++ which tells me hateful number wich acording to my teacher a hateful number is some number which converted to binary has an odd numbers of ones for example 2 (10) 4(100) 7(111) 8 (1000) 11(1011)

So I need to develop a program that do this

Enter a number and then tell me all hateful numbers before that number entered Hope you can understand this

Thanks

Ok so I found this code on a blog

// C++ program to generate binary numbers from 1 to n
#include <iostream>
#include <queue>
using namespace std;

// This function uses queue data structure to print binary numbers
void generatePrintBinary(int n)
{
// Create an empty queue of strings
queue<string> q;

// Enqueue the first binary number
q.push("1");

// This loops is like BFS of a tree with 1 as root
// 0 as left child and 1 as right child and so on
while (n--)
{
    // print the front of queue
    string s1 = q.front();
    q.pop();
    cout << s1 << "\n";

    string s2 = s1;  // Store s1 before changing it

    // Append "0" to s1 and enqueue it
    q.push(s1.append("0"));

    // Append "1" to s2 and enqueue it. Note that s2 contains
    // the previous front
    q.push(s2.append("1"));
}
}
// Driver program to test above function
    int main()
    {
    int n;
    printf("Por favor ingrese un numero\n");
    scanf(" %d" ,&n);
    generatePrintBinary(n);
    return 0;
    }

I was only to an specify number and I modified to let the user put any number now I need to only print odd binary numbers how I can do that?

1 Answers1

0

Well you would need a function that divides your decimal number by 2 until 0 and increments the remainder of each division. If the result is odd, you have your hateful number.

something like:

int res = 0;
while (number > 0)
{
    res += number % 2; // add the remainder of the division by 2 to res
    number = number / 2; 
}
if (res % 2 == 1) // if res is odd, its modulo by 2 is 1
    // hateful number

Also if you are familiar with bitwise operations, I know one who could do the trick:

int res;
for (res = 0; number > 0; res++)
{
    number &= number - 1;
}
if (res % 2 == 1)
    // hateful number

EDIT :

You could first check for the number of 1s as I showed and then decide to print it if it is as you say a 'hateful' number. To print it, the following snippet may be of help:

std::vector<int> vec;
while(number > 0)
{
    vec.push_back(number % 2);
    number = number / 2;
}

Note that the vector will be reversed in that 6 for example will be 011 instead of 110. You can either reverse it with std::reverse of the algorithm header, or print it in reverse order.

blakelead
  • 1,780
  • 2
  • 17
  • 28