Open
Conversation
nodchip
reviewed
Mar 16, 2026
| int x = k - 1; | ||
| int parity = 0; | ||
|
|
||
| while (x > 0) { |
There was a problem hiding this comment.
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() やそのほかの関数、分割統治法とビット演算を用いた求め方は、ソフトウェアエンジニアの常識にぎりぎり入っているかいないかくらいだと思います。
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
問題
https://leetcode.com/problems/k-th-symbol-in-grammar/description/
次の問題
Split BST