Conversation
tokuhirat
reviewed
Oct 4, 2025
| else | ||
| 1 | ||
| end | ||
| end |
There was a problem hiding this comment.
私が慣れてないからかもしれませんが、ネストされた長い if 式の値が返り値になっているのが初見では少し読みにくかったです。慣れている人は L17を見て返り値になりそうと読むので大丈夫かもしれないとも思いました。
Owner
Author
There was a problem hiding this comment.
コメントありがとうございます!
# @param {Integer} n
# @param {Integer} k
# @return {Integer}
def kth_grammar(n, k)
return -1 if n <= 0 || k <= 0 || k > 2 ** (n - 1) # 不正な値は-1を返す
return 0 if n == 1 && k == 1
prev = kth_grammar(n - 1, (k + 1) / 2)
return 1 if prev.zero? && k.even?
return 0 if prev.zero? || k.even?
1
endこんな感じでネストは浅くなりますが、これはこれで対称性が少し見えづらいですが好みの問題かもしれません。
There was a problem hiding this comment.
そうですね。色々書き方があり好みの問題だと思います。
個人的には step2 で書かれているような感じが好みです。
symbol = kth_grammar(n - 1, (k + 1) / 2)
if k.even?
symbol ^= 1
end
symbol
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.
解いた問題
779. K-th Symbol in Grammar
使用言語
Ruby
次に解く問題
3. Longest Substring Without Repeating Characters