From 11d4ac9429fe2341670cae75ee086b72868f7389 Mon Sep 17 00:00:00 2001 From: Samir Paul Date: Tue, 3 May 2022 13:38:48 +0530 Subject: [PATCH] bit manipulation --- .../08. Find Kth Bit in Nth Binary String.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 17_Bit-Manipulation/08. Find Kth Bit in Nth Binary String.py diff --git a/17_Bit-Manipulation/08. Find Kth Bit in Nth Binary String.py b/17_Bit-Manipulation/08. Find Kth Bit in Nth Binary String.py new file mode 100644 index 00000000..b2320b20 --- /dev/null +++ b/17_Bit-Manipulation/08. Find Kth Bit in Nth Binary String.py @@ -0,0 +1,35 @@ +# https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/ + + +''' +# Brute Force Solution +class Solution: + def findKthBit(self, n: int, k: int) -> str: + + def revinv(s): + s = list(s) + for i in range(len(s)): + if s[i] == '0': + s[i] = '1' + else: + s[i] = '0' + s = ''.join(s) + s = s[::-1] + return s + + dp = ['0'] * n + dp[0] = '0' + for i in range(n): + dp[i] = dp[i-1] + '1' + revinv(dp[i-1]) + + return dp[-1][k-1] + +# Time: O(n^2) +# Space: (n) +''' + + +# Optimal Solution: +class Solution: + def findKthBit(self, n, k): + return str(k / (k & -k) >> 1 & 1 ^ k & 1 ^ 1) \ No newline at end of file