Last active
April 23, 2019 11:56
-
-
Save vkopichenko/5728181468052eb786f5b5f57e77e1bc to your computer and use it in GitHub Desktop.
Побитовые операции
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://dl.gsu.by/task.jsp?nid=1835989&cid=19 | |
// Гомельская гор.\2019\Областная 1-9 кл, 19 апреля\5-9 кл\8 - "Двоичные числа-2" 218491 Долинский М.С., апрель 2018 | |
#include "bits/stdc++.h" | |
using namespace std; | |
typedef long long int64; | |
int main() { | |
ifstream cin("BINARY.IN"); | |
ofstream cout("BINARY.OUT"); | |
int64 x; | |
cin >> x; | |
std::cout << bitset<64>(x) << ' ' << x << endl; | |
set<int64> used; | |
for (int i = sizeof(x)*8; i > 0; --i) { | |
if ((x >> i-1) == 0) continue; // если до i-ой позиции все нули, идём дальше | |
int64 mask = 0; | |
for (int j = i - 1; j >= 0; --j) { | |
mask |= 1LL << j; // формируем маску для для бит с i-го по j-ый | |
// mask = (1ll << i) - 1; // второй способ получения маски, не работает при i==64 | |
// mask = (int64) -1 >> (64 - i); // третий способ получения маски | |
int64 s = (x & mask) >> j; // вырезаем биты числа с i-го до j-го | |
used.insert(s); // множество не принимает лишние дубли | |
} | |
} | |
int64 sum = 0; | |
for (int64 i : used) { | |
std::cout << bitset<64>(i) << ' ' << i << endl; // отладочная печать на экран | |
sum += i; | |
} | |
cout << sum; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment