1017-Convert to Base -2-Py All-in-One by Talse
Get it Done, Make it Better, Share the Best -- Talse\nI). As Positive Base\n| O(T): O(lgn) | O(S): O(1) | Rt: 32ms | \npython\n    def baseNeg2(self, N: int) ->
**Get it Done, Make it Better, Share the Best -- Talse**\n**I). As Positive Base**\n| O(T): O(lgn) | O(S): O(1) | Rt: 32ms | \n```python\n    def baseNeg2(self, N: int) -> str:\n        if N == 0: return \'0\'\n        rst = []\n        while N:\n            rst.append(N % 2)\n            N = -(N // 2)\n        rst.reverse()\n        return \'\'.join(map(str, rst))\n```\n\nAlternative: I know you find this solution very hard to understand. Here is the rescue. | Rt: 32ms |\n```python\n    def baseNeg2(self, N: int) -> str:\n        if N == 0: return \'0\'\n        rst = []\n        while N:\n            rst.append(N % 2)\n            # math.ceil(a/b) = -(-a // b) => math.ceil(N / (-2))\n            #the only difference between -2 and 2 is: when divider is negative, it round toward the lower bound which is negative. However, we need the result round toward 0;\n            N = -(-N // (-2))\n        rst.reverse()\n        return \'\'.join(map(str, rst))\n```\nReferrence: https://leetcode.com/problems/convert-to-base-2/discuss/265507/JavaC%2B%2BPython-2-lines-Exactly-Same-as-Base-2\n\n\n**II). Masking**\n| O(T): O(1) | O(S): O(1) | Rt: 32ms | \n```python\n    def baseNeg2(self, N: int) -> str:\n        masks = [1 << i for i in range(1, 33, 2)]\n        for m in masks:\n            if N & m: N += 2 * m\n        return bin(N)[2:]\n```\nReferrence: https://leetcode.com/problems/convert-to-base-2/discuss/265688/4-line-python-clear-solution-with-explanation\n\n\n**III). General Negative Base Coversion**\n| O(T): O(lgn) | O(S): O(1) | Rt: 32ms | \n```python\n    def baseNeg2(self, N: int) -> str:\n        if not N: return \'0\'\n        rst, base = [], -2\n        while N:\n            N, mod = divmod(N, base)\n            #round toward 0 instead of the default "round toward lower bound"\n            if mod < 0: mod, N = mod + -base, N+1\n            rst.append(mod)\n        rst.reverse()\n        return \'\'.join(map(str, rst))\n```\nReferrence: https://leetcode.com/problems/convert-to-base-2/discuss/265544/C%2B%2B-Geeks4Geeks; https://www.***.org/convert-number-negative-base-representation/;\n
[]