Skip to content

Create 779. K-th Symbol in Grammar.md#46

Open
fuga-98 wants to merge 1 commit into
mainfrom
779.-K-th-Symbol-in-Grammar
Open

Create 779. K-th Symbol in Grammar.md#46
fuga-98 wants to merge 1 commit into
mainfrom
779.-K-th-Symbol-in-Grammar

Conversation

@fuga-98
Copy link
Copy Markdown
Owner

@fuga-98 fuga-98 commented May 15, 2025


https://github.com/hroc135/leetcode/pull/44/files

- bitの内部実装を読んでいる。
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ビットを数えるのは CPU によっては専用の命令が用意されていたりするので、それの一番下のビットを見るだけの場合もありますね。

def kthGrammar(self, n: int, k: int) -> int:
if n == 1:
return 0
return self.kthGrammar(n - 1, (k + 1) // 2) ^ ((k & 1) ^ 1)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

自分なら ^ (k % 2 == 0) にすると思いました。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

あ、下に書いてありましたね。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ここまでやると読みにくいですね。

def kthGrammar(self, n: int, k: int) -> int:
result = 0

while n > 1:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

while k > 1: で良さそうです。bit_count を使った解法で n に対して何もしないのと一緒で、k <= 2**(n-1) さえ分かっていればあとは k に対してのみ処理すればよいです。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます!言われてみればそうですね!

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.

3 participants