Find and output all integers in the range from 2 to n for which the number of zeros in the binary representation of the number is less than the number of ones.

  • one
    Are there leading zeroes or not? - alexlz
  • 3
    And the question is what? - dzhioev
  • It is necessary to check: if in the binary prefix the number is more units than zeros, then output this number. - nullptr pm
  • where in the sentence "it is necessary to check: if in the binary prefix the number is more than one than zero, then output this number" is a question mark? - fogbit
  • @fogbit question mark in this case is not needed. <br /> @ qwerty12359 you can not react immediately to any offtopic <br /> So what is the essence of the problem? If this is a training task, then just for each number, go through all the bits, count whom. - cy6erGn0m

3 answers 3

Well, like this (insignificant zeros are not counted)

#include <iostream> #include <vector> using namespace std; int main (void) { int n; vector<int> v; cin >> n; for(int i=2; i<=n; i++) { int diff=0, k = i; while(k) { if(k & 1) diff--; else diff++; k >>= 1; } if(diff < 0) v.push_back(i); } vector<int>::iterator it = v.begin(); while(it < v.end()) { cout << *it++; if(it < v.end()) cout << " "; } cout << endl; } 

    Well, nobody asked for ascending output, so you can do this:

     #include <stdio.h> int main() { unsigned n, o = 0, z = 1, p = 0, q, c; scanf("%u", &n); for (q=1; q<2*n; ++q) { c = q ^ (q>>1); if (c & (p^c)) ++o, --z; else --o, ++z; p = c; if (o > z && c < n && c != 1) printf("%d ", c); if (o == 1) ++z; } return 0; } 

      I'm starting to code, so I think to put my decision on C:

       #define _CRT_SECURE_NO_WARNINGS #include "stdio.h" int main() { int n = 0, num10 = 2, num10f = 0; int i = 0, j = 0; printf("Enter n. [2;n]\n"); scanf("%d", &n); for (num10; num10 <= n; num10++) { num10f = num10; while (num10f / 2 != 0) { if (num10f % 2 == 0) i++; else j++; num10f /= 2; } if (j >= i) { printf("%d\n", num10); } j = 0, i = 0; } getchar(); return 0; } 
      • I annul my previous comment - the question was posed by an experienced forum participant, surprisingly clumsily, which put me in a deadlock, nevertheless everything said in the comment about the gentlemen's agreements at the forum is valid. - Alexander Muksimov