Website Summary Files Commits Branches @commit @diff @stats
path: root / pract_KN / pract. 07 / solutions.cpp
blob: dc1937403c6fb86efc9bd2abd19ef5d6208beba1 (plain) (blame)
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
void getBitwiseRepresentation(int n) {
	for (int i = 31; i >= 0; --i)
		std::cout << ((n & (1 << i)) != 0);
}

void flipFourthBit(int& n) {
	int mask = 1 << 3;
	n = n ^ mask;
}

int numberOfZeroesInBinaryRepresentation(int n) {
	int cnt = 0;
	for (int i = 0; i < 32; i++)
		cnt += ((n & (1 << i)) == 0);

	return cnt;
}

void setBit(int& n, int bitPosition, bool newBitValue) {
	int mask = 1 << bitPosition;
	bool oldBitIsOne = ((mask & n) != 0);
	if (oldBitIsOne ^ newBitValue)	n = n ^ mask;
}

void printSubset(int arr[], int length, int indexOfSet) {
	std::cout << "[";
	int commas = 0;
	int numberOfOnes = 32 - numberOfZeroesInBinaryRepresentation(indexOfSet);

	for (int i = 0; i < length; i++) {
		if (((indexOfSet & (1 << i)) != 0)) {
			std::cout << arr[i];

			if (++commas < numberOfOnes)
				std::cout << ", ";
		}
	}
	std::cout << ']' << std::endl;
}

void generateSubsets(int arr[], int length) {
	int border = 1 << length;
	for (int i = 0; i < border; i++)
		printSubset(arr, length, i);
}

//bonus: function to change the sign of a number
void changeSign(int& n) {
  n = ~n + 1;
}