Skip to content

Conversation

@docto-rin
Copy link
Owner

# 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:
Copy link

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.

と書かれており、どちらが良いか判断できませんでした。

チームの平均的な書き方に合わせることをおすすめします。

Copy link

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
Copy link

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
Copy link

Choose a reason for hiding this comment

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

ちょっとこの関数の具体的なユースケースは思い付かないのですが、一応nを与えられたときにあり得ない(n行目に存在しない)kの値だったらエラーなどで弾いても良さそうな気がしました。

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.

4 participants