-
Notifications
You must be signed in to change notification settings - Fork 0
Create 0779-k-th-symbol-in-grammar.md #47
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
| # is odd num of 1 when expressing integer (k - 1) in (n - 1) bit? | ||
| is_odd = False | ||
| for shift in range(n - 1): | ||
| if k - 1 >> shift & 1: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
自分が C++ で書く場合は、演算子の優先順位を明示的に表現するために、
if (k - 1) >> (shift & 1):と書くと思います。一方、 Google Python Style Guide には
https://google.github.io/styleguide/pyguide.html#33-parentheses
Use parentheses sparingly.
It is fine, though not required, to use parentheses around tuples. Do not use them in return statements or conditional statements unless using parentheses for implied line continuation or to indicate a tuple.
と書かれており、どちらが良いか判断できませんでした。
チームの平均的な書き方に合わせることをおすすめします。
There was a problem hiding this comment.
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: | ||
| bit = 0 | ||
| for shift in range(k.bit_length()): | ||
| bit ^= k - 1 >> shift & 1 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
好みかもしれませんが、k - 1 & 1 << shiftとした方がわかりやすく思いました。
| ```python3 | ||
| class Solution: | ||
| def kthGrammar(self, n: int, k: int) -> int: | ||
| return (k - 1).bit_count() % 2 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ちょっとこの関数の具体的なユースケースは思い付かないのですが、一応nを与えられたときにあり得ない(n行目に存在しない)kの値だったらエラーなどで弾いても良さそうな気がしました。
この問題:https://leetcode.com/problems/k-th-symbol-in-grammar/
次の問題:https://leetcode.com/problems/split-bst/