-
Notifications
You must be signed in to change notification settings - Fork 0
/
countBits.cpp
90 lines (63 loc) · 1.74 KB
/
countBits.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
countBits.cpp
Aulas particulares de programação C++
CodeWars exercise:
Write a function that takes an integer as input, and returns the
number of bits that are equal to one in the binary representation
of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010,
so the function should return 5 in this case
*/
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <cstdlib>
using std::_Exit;
#include <sstream>
using std::istringstream;
#include <string>
using std::string;
unsigned int countBits(unsigned long long n);
int main(){
unsigned long long nr;
string nrStr;
cout << "Entre com o numero: ";
cin >> nrStr;
// validando a entrada
if( nrStr[0] == '-') {
cout << "invalid input" << endl;
_Exit(EXIT_FAILURE);
}
for(int i=0;i<nrStr.length();i++){
if( !isdigit(nrStr[i]) ) {
cout << "invalid input" << endl;
_Exit(EXIT_FAILURE);
}
}
// convertendo a entrada string em numero
istringstream convert(nrStr);
convert >> nr;
cout << "Nr de 1s no binario: " << countBits(nr) << endl;
return 0;
}
unsigned int countBits(unsigned long long n){
unsigned int bits = 0;
// array to store binary number
unsigned long long binaryNum[32];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
if( binaryNum[i] == 1 ) bits++;
n = n / 2;
i++;
}
// setting binary array in reverse order
for (int j = i - 1; j >= 0; j--)
binaryNum[j];
return bits;
}
// end of countBits.cpp