ビット演算共通の仕上げ作業(C ++達成するために)

ナンバー1

解決策1:

n & 1右端が1か否かを判断し、一番右の1権利を決定するために継続し、N = 0になるまで繰り返されます。時間の複雑さがありますO(log2n)

#include <iostream>
using namespace std;
int main() {
    int n = 0b1101, cnt = 0;
    while (n) {
        cnt += n & 1;
        n >>= 1;
    }
    cout << cnt << endl;
    return 0;
}

解決策2:

n & (n - 1)消去可能右端1は、n = 0になるまで繰り返されます。時間の複雑さがされO(count)、数1の数に応じて、この方法は、最初よりも優れています。

#include <iostream>
using namespace std;
int main() {
    int n = 0b1101, cnt = 0;
    while (n) {
        n = n & (n - 1);
        ++cnt;
    }
    cout << cnt << endl;
    return 0;
}

ビットが1又は0であるかどうかを決定するため

右からk番目の位置を分析すること、(n >> (k - 1)) & 1

#include <iostream>
using namespace std;
int main() {
    int n = 0b1101;
    cout << (n >> 1 & 1) << endl;  // 第 2 位为 0
    cout << (n >> 2 & 1) << endl;  // 第 3 位为 1
    return 0;
}

逆ビット

右のk番目の位置から反転、n ^ (1 << (k - 1))

#include <iostream>
using namespace std;
int main() {
    int n = 0b1101;
    cout << (n ^ (1 << 2)) << endl;  // 反转第 3 位 -> 1001
    cout << (n ^ (1 << 1)) << endl;  // 反转第 2 位 -> 1111
    return 0;
}

いくつかの実用的なルール

ビットごとのXOR と同じ数の二倍(n ^ x ^ x)、変わりません。

#include <iostream>
using namespace std;
int main() {
    int n = 13, x = 666;
    cout << (n ^ x ^ x) << endl;  // 仍然是 13
    return 0;
}

所定の位置に金型でビット単位、パリティ決意、より効率的。n & 1結果が偶数である結果が奇数で1であり、0です。

#include <iostream>
using namespace std;
int main() {
    cout << (4 & 1) << endl;
    cout << (5 & 1) << endl;
    return 0;
}

左にK kビットは、2のk乗だけ右に2、kビットの電力を取ります。このようなマージソートとして、分割統治戦略では一般的です。

#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;

void partition(int a[], int l, int m, int r) {
    int *t = new int[r - l + 1];
    int i = l, j = m + 1, k = 0;
    while (i <= m && j <= r) t[k++] = a[i] < a[j] ? a[i++] : a[j++];
    while (i <= m) t[k++] = a[i++];
    while (j <= r) t[k++] = a[j++];
    for (int i = l; i <= r; ++i) a[i] = t[i - l];
    delete[] t;
}

void merge_sort(int a[], int l, int r) {
    if (l < r) {
        int m = (l + r) >> 1;  // 相当于 (l + r) / 2
        merge_sort(a, l, m);
        merge_sort(a, m + 1, r);
        partition(a, l, m, r);
    }
}

int main() {
    srand(time(0));
    int a[20];
    for (int i = 0; i < 20; ++i) a[i] = rand() % 100;
    merge_sort(a, 0, 19);
    for (int i = 0; i < 20; ++i) cout << a[i] << " ";
    return 0;
}
リリース元の4件の記事 ウォン称賛83 ビュー6754

おすすめ

転載: blog.csdn.net/weixin_43231262/article/details/103951502