-9

I need to program a method that will pass two int numbers i1 and i2 and return the number that has more ones in its binary representation.

  • Keep in mind that "decimal" and "binary" refer to how a value is written as **text**. So converting decimal to binary means converting **text** to **text**. An `int` value is not decimal or binary; it's `int`. You can convert it to text with a decimal representation (for example, 128) and you can convert it to text with a binary representation (10000000). – Pete Becker May 16 '20 at 12:57

2 Answers2

0

This thread should help you get the binary representations C++ - Decimal to binary converting later with your binary arrays you can use

#include <numeric>
std::accumulate(binaryArr, binaryArr + sizeof(binaryArr)/sizeof(binaryArr[0]), 0);

to count the number of ones. Also this really looks like solve my homework for me type of question, try reaserching and solving the problem yourself, and then asking your question with some code samples. This way you actually learn

SzymonO
  • 432
  • 3
  • 15
  • The code in that link is **horrible** (including undefined behavior, so all bets are off). And it doesn't convert decimal to binary; it converts an `int` value to a binary representation. The conversion from decimal to `int` occurs in the stream extractor `std::cin >> a1;`. – Pete Becker May 16 '20 at 13:01
  • Yes, but the anwsers provide a decent code and his task is to count the ones so I think representation is enough – SzymonO May 16 '20 at 16:00
0

first of all you should find way to find how many ones contains number(count_ones_binary function), and then you just use this function to solve you problem

#include <iostream>

int count_ones_binary(int x)
{
    int res = 0;
    while (x != 0)
    {
        if (x % 2 != 0)
            res++;
        x /= 2;
    }
    return res;
}

void more_ones_binary(int i1, int i2)
{
    int count_i1 = count_ones_binary(i1);
    int count_i2 = count_ones_binary(i2);
    if (count_i1 > count_i2)
        std::cout << "i1 have more ones\n";
    else if (count_i1 < count_i2)
        std::cout << "i2 have more ones\n";
    else std::cout << "equal\n";
}
drKazeev
  • 1
  • 1
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – Ardent Coder May 16 '20 at 11:41