diff --git a/bit_manipulation/flip_bit/flip_bit_solution.ipynb b/bit_manipulation/flip_bit/flip_bit_solution.ipynb index 6b7889f..aad317f 100644 --- a/bit_manipulation/flip_bit/flip_bit_solution.ipynb +++ b/bit_manipulation/flip_bit/flip_bit_solution.ipynb @@ -118,62 +118,28 @@ "outputs": [], "source": [ "class Bits(object):\n", - "\n", " MAX_BITS = 32\n", " \n", - " def _build_seen_list(self, num):\n", - " seen = []\n", - " looking_for = 0\n", - " count = 0\n", - " for _ in range(self.MAX_BITS):\n", - " if num & 1 != looking_for:\n", - " seen.append(count)\n", - " looking_for = not looking_for\n", - " count = 0\n", - " count += 1\n", - " num >>= 1\n", - " seen.append(count)\n", - " return seen\n", - " \n", " def flip_bit(self, num):\n", " if num is None:\n", - " raise TypeError('num cannot be None')\n", - " if num == -1:\n", - " return self.MAX_BITS\n", - " if num == 0:\n", - " return 1\n", - " seen = self._build_seen_list(num)\n", - " max_result = 0\n", - " looking_for = 0\n", - " for index, count in enumerate(seen):\n", - " result = 0\n", - " # Only look for zeroes\n", - " if looking_for == 1:\n", - " looking_for = not looking_for\n", - " continue\n", - " # First iteration, take trailing zeroes\n", - " # or trailing ones into account\n", - " if index == 0:\n", - " if count != 0:\n", - " # Trailing zeroes\n", - " try:\n", - " result = seen[index + 1] + 1\n", - " except IndexError:\n", - " result = 1\n", - " # Last iteration\n", - " elif index == len(seen) - 1:\n", - " result = 1 + seen[index - 1]\n", + " raise TypeError\n", + " run1 = 0\n", + " run2 = 0\n", + " best = 0\n", + " \n", + " as_bin = format(num if num >= 0 else (1 << 32) + num, '032b')\n", + " \n", + " for c in as_bin:\n", + " if c == '1':\n", + " run1 += 1\n", + " run2 += 1\n", " else:\n", - " # One zero\n", - " if count == 1:\n", - " result = seen[index + 1] + seen[index - 1] + 1\n", - " # Multiple zeroes\n", - " else:\n", - " result = max(seen[index + 1], seen[index - 1]) + 1\n", - " if result > max_result:\n", - " max_result = result\n", - " looking_for = not looking_for\n", - " return max_result" + " if run2 > best:\n", + " best = run2\n", + " run2 = run1 + 1\n", + " run1 = 0\n", + " return max(run2, best)\n", + " " ] }, {