Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Convert to Base -2

$
0
0

题目描述:

LeetCode 1017. Convert to Base -2

Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two).

The returned string must have no leading zeroes, unless the string is "0".

Example 1:

Input: 2Output: "110"Explantion: (-2) ^ 2 + (-2) ^ 1 = 2

Example 2:

Input: 3Output: "111"Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3

Example 3:

Input: 4Output: "100"Explantion: (-2) ^ 2 = 4

Note:

  1. 0 <= N <= 10^9

题目大意:

将整数N转换为-2进制

解题思路:

位运算

Python代码 (版本1):

class Solution(object):
    def baseNeg2(self, N):
        """
        :type N: int
        :rtype: str
        """
        pow = 1
        ans = ''
        while N:
            if N & abs(pow):
                ans += '1'
                N -= pow
            else:
                ans += '0'
            pow *= -2
        return ans[::-1] or "0"

Python代码 (版本2):

class Solution(object):
    def baseNeg2(self, N):
        """
        :type N: int
        :rtype: str
        """
        ans = ''
        while N:
            ans += str(N & 1)
            N = -(N >> 1)
        return ans[::-1] or "0"

附录 (进制转换对照):

 12345678
Base20000100010000110010000101001100011101000
Base-20000100110001110010000101110101101111000

 


Viewing all articles
Browse latest Browse all 559

Trending Articles