Tuesday, August 25, 2015

Leetcode 190. Reverse Bits

https://leetcode.com/problems/reverse-bits/

Two solutions. String one and bit operation one.

Solution 1:
# T:O(n) S:O(1)
class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        s = bin(n)
        s = s[2:]
        length = len(s)
        zeros = 32 - len(s)
        s = '0'*zeros + s
        s = s[::-1]
        return int(s,2)
Run Time: 56 ms

Solution 2:
# T:O(n) S:O(1)
class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        result = 0
        for i in xrange(32):
            result <<= 1
            result |= n & 1
            n >>= 1
        return result
Run Time: 60 ms

No comments:

Post a Comment