Skip to content

779. K-th Symbol in Grammar#46

Open
dxxsxsxkx wants to merge 1 commit into50_pow_xnfrom
779_kth_symbol_in_grammar
Open

779. K-th Symbol in Grammar#46
dxxsxsxkx wants to merge 1 commit into50_pow_xnfrom
779_kth_symbol_in_grammar

Conversation

@dxxsxsxkx
Copy link
Copy Markdown
Owner

int x = k - 1;
int parity = 0;

while (x > 0) {
Copy link
Copy Markdown

@nodchip nodchip Mar 16, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C++20 からは std::popcount() が使えるようです。
https://cpprefjp.github.io/reference/bit/popcount.html
古くは、 gcc では __builtin_popcount() が使われていました。

Visual Studio の C++ コンパイラーでは __popcnt() が提供されています。
https://learn.microsoft.com/ja-jp/cpp/intrinsics/popcnt16-popcnt-popcnt64?view=msvc-170

「ハッカーのたのしみ: 本物のプログラマはいかにして問題を解くか」には、分割統治法でビット演算で求める方法が書かれていたと思います。
https://amzn.asia/d/0drAmtQm
以下は ChatGPT に書いてもらったものです。

#include <cstdint>

int popcount(uint32_t x) {
    constexpr uint32_t M1 = 0x55555555u; // 0101...
    constexpr uint32_t M2 = 0x33333333u; // 0011...
    constexpr uint32_t M4 = 0x0F0F0F0Fu; // 00001111...
    constexpr uint32_t M8 = 0x00FF00FFu;
    constexpr uint32_t M16 = 0x0000FFFFu;

    x = (x & M1) + ((x >> 1) & M1);   // 2-bit sums
    x = (x & M2) + ((x >> 2) & M2);   // 4-bit sums
    x = (x & M4) + ((x >> 4) & M4);   // 8-bit sums
    x = (x & M8) + ((x >> 8) & M8);   // 16-bit sums
    x = (x & M16) + ((x >> 16) & M16); // 32-bit sums

    return x;
}

標準ライブラリの std::popcount() やそのほかの関数、分割統治法とビット演算を用いた求め方は、ソフトウェアエンジニアの常識にぎりぎり入っているかいないかくらいだと思います。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants