From ff08ac37a7ec44afcae45b3b3b13d13dfe1a59b4 Mon Sep 17 00:00:00 2001 From: potrue <126231160+potrue@users.noreply.github.com> Date: Thu, 14 Aug 2025 23:38:40 +0900 Subject: [PATCH 1/2] 779. K-th Symbol in Grammar https://leetcode.com/problems/k-th-symbol-in-grammar/description/ --- 779/779.md | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 779/779.md diff --git a/779/779.md b/779/779.md new file mode 100644 index 0000000..587d091 --- /dev/null +++ b/779/779.md @@ -0,0 +1,75 @@ +## 何も見ずに解いてみる + +```cpp +class Solution { +public: + int kthGrammar(int n, int k) { + if (k == 1) return 0; + int k_parity = k & 1; + if (k_parity == 0) k_parity = 2; + int k_prev = k + 1 >> 1; + int prev = kthGrammar(n - 1, k_prev); + if (prev == 0 && k_parity == 1 || prev == 1 && k_parity == 2) { + return 0; + } else { + return 1; + } + } +}; +``` + +1-indexedに慣れてなくて難しい + +## 他の人のコードを見てみる + +https://github.com/olsen-blue/Arai60/pull/47/files +https://github.com/Fuminiton/LeetCode/pull/46/files +https://github.com/ryosuketc/leetcode_arai60/pull/35/files +https://github.com/Ryotaro25/leetcode_first60/pull/49/files + +後半部分が前半部分を反転したものになっている。なるほど。 +ビットの数が反転した数であるというのも言われてみればたしかに。2で割ったときに余りが出る回数と考えると納得。 + +popcountの実装っぽいやつを一つ見つけました +https://github.com/llvm/llvm-project/blob/main/flang/include/flang/Common/bit-population-count.h +まとめてシフトしたほうが1個ずつシフトして数を数えるよりもCPUに対しての命令の数が少なくできてうれしいということですかね? + +leetcodeでいろいろ実行していたら言われたが、`<<`や`>>`が`-`や`+`よりも優先度が低いというのは結構意外かも。 +https://en.cppreference.com/w/cpp/language/operator_precedence.html + +1-indexedのままで記述しようとしたら下のコードみたいになりました。結構大変 + +```cpp +class Solution { +public: + int kthGrammar(int n, int k) { + if (k < 0 || k > 1 << (n - 1)) { + throw std::invalid_argument("index k doesn't exist in the row n"); + } + int result = 0; + while (k > 1) { + if (!(k & 1)) { + result ^= 1; + } + k = (k + 1) >> 1; + } + return result; + } +}; +``` + +https://cpprefjp.github.io/reference/bit/popcount.html +https://learn.microsoft.com/ja-jp/cpp/cpp/data-type-ranges?view=msvc-170 + +## 最終コード +```cpp +class Solution { +public: + int kthGrammar(int n, int k) { + if (n <= 0 || k <= 0 || k > 1 << (n - 1)) { + throw std::invalid_argument("invalid argument"); + } + return std::popcount((unsigned int)k - 1) & 1; + } +}; +``` From fd184d5dbbde71e4070adc197d33d9dc3e1c7360 Mon Sep 17 00:00:00 2001 From: potrue <126231160+potrue@users.noreply.github.com> Date: Thu, 14 Aug 2025 23:41:51 +0900 Subject: [PATCH 2/2] Update 779.md --- 779/779.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/779/779.md b/779/779.md index 587d091..78de7af 100644 --- a/779/779.md +++ b/779/779.md @@ -43,9 +43,6 @@ https://en.cppreference.com/w/cpp/language/operator_precedence.html class Solution { public: int kthGrammar(int n, int k) { - if (k < 0 || k > 1 << (n - 1)) { - throw std::invalid_argument("index k doesn't exist in the row n"); - } int result = 0; while (k > 1) { if (!(k & 1)) {