Liczenie ile jest jedynek w systemie dwójkowym, po podaniu liczby w systemie dziesiętnym

0

Mam problem, chcę zrobić program, który na wejściu dostaje liczbę w systemie dziesiętnym, a na wyjściu daje nam sumę jedynek. Zrobiłem kod, który PRZEKRACZA LIMIT CZASU PROSZĘ O SZYBKĄ POMOC

 #include <iostream>
using namespace std;

int main() {

int a;
cin >> a;
int b;
int c;
x:	if(a%2==1){
		c=b+1;
		a=a/2;
	}
		if(a=0){
			cout<<b;
			getchar();
		}else{
			goto x;
		}

	return 0;
}
0
        c=b+1;

Undefined behaviour. wartość b jest nieokreślona. Dalej można nie czytać.

0
Azarien napisał(a):
        c=b+1;

Undefined behaviour. wartość b jest nieokreślona. Dalej można nie czytać.

OK, ale to znaczy, że na początku ma być
```cpp
int b=0;

0
  • zamień goto na pętlę
  • if(a=0)

Potrzebujesz jednego ifa w pętli, a limit czasu przekracza pewnie dlatego, że goto jest nieskończony :P

0
#include <iostream>
using namespace std;

int CountBitSet(int x)
{  // zrob sam
}
 
int main() {
    int a;
    while (cin >> a) {
         cout << CountBitSet(a) << '\n';
    }
    return 0;
}
0
#include <stdio.h>
#include <assert.h>

int countBits(int val) {
  if (val == 0x54) {
  	return 3;
  } else if ((val & 1) == 0) {
  	int result = 0;
  	while(val > 0) result++, val &= (val - 1);
  	return result;
  } else if (val + 10 < 16) {
  	int result = 0;
  	while(val > 0) result += (val & 1), val >>= 1;
  	return result;
  } else {
  	return (val == 0 ? 0: (val % 2) + countBits(val >> 1)); 
  }
}
  
void test(int value, int expected) {
	int count = countBits(value);
	//assert(count==expected);
	printf("For %04x bit count = %d\n", value, count);
}  

int main(void) {
	test(0x55, 4);
	test(0x07, 3);
	test(0x60, 2);
	test(0x01, 1);
	return 0;
}

https://ideone.com/3ya1E8

0

Sprawdź te implementacje :)

int pop(unsigned x) {
    x = x - ((x >> 1) & 0x55555555);
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
    x = (x + (x >> 4)) & 0x0F0F0F0F;
    x = x + (x >> 8);
    x = x + (x >> 16);
    return x & 0x0000003F;
}
int pop(unsigned x) { 
    unsigned n;
    n = (x >> 1) & 033333333333;
    x = x - n;
    n = (n >> 1) & 033333333333;
    x = x - n;
    x = (x + (x >> 3)) & 030707070707;
    return x%63;
}
int pop(unsigned x) {
    unsigned n;
    
    n = (x >> 1) & 0x77777777; 
    x = x - n;
    n = (n >> 1) & 0x77777777; 
    x = x - n;
    n = (n >> 1) & 0x77777777;
    x = x - n;
    x = (x + (x >> 4)) & 0x0F0F0F0F; 
    x = x*0x01010101;
    return x >> 24;
}
int pop(unsigned x) { 
    int n;
    n = 0;
    while (x ! = 0) {         
        n = n + 1;
        x= x& (x - 1);
    } 
    return n;
}
int pop(unsigned x) {
    unsigned long long y;
    y = x * 0x0002000400080010ULL; 
    y = y & 0x1111111111111111ULL; 
    y = y * 0x1111111111111111ULL; 
    y = y >> 60;
    return y;
}

Źródło: Hacker's Delight

1 użytkowników online, w tym zalogowanych: 0, gości: 1