Skip to content

Instantly share code, notes, and snippets.

@dapangmao
Last active August 29, 2015 14:07
Show Gist options
  • Save dapangmao/25dcf6eeb5bdc6049540 to your computer and use it in GitHub Desktop.
Save dapangmao/25dcf6eeb5bdc6049540 to your computer and use it in GitHub Desktop.
Bit manipulation
  • Digit saves spaces
#-------------------------------------------------------------------------------
# Name:        Single Number
# Purpose:
#
#        Given an array of integers, every element appears twice except for one.
#        Find that single one.
#
#        Note:
#        Your algorithm should have a linear runtime complexity.
#        Could you implement it without using extra memory?
#-------------------------------------------------------------------------------
def singleNumber(A):
    return reduce(operator.xor, A)
  • Binary basics
#-------------------------------------------------------------------------------
# Name:        Add Binary
# Purpose:
#        Given two binary strings, return their sum (also a binary string).
#
#        For example,
#        a = "11"
#        b = "1"
#        Return "100".
#-------------------------------------------------------------------------------
def addBinary(a, b):
    summ = 0
    for n in [a, b]:
        rst = 0
        for x in n:
            rst = rst*2 + int(x)
        summ += rst
    return bin(summ)[2:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment