首页 > 代码库 > Personal Leetcode solution(Python)

Personal Leetcode solution(Python)

GitHub: 

https://github.com/seventheli/LeetCode-Practice

singleNumber

Core: A XOR B XOR A XOR C XOR B = C

class Solution(object):    def singleNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        result = 0        for each in range(len(nums)):            result ^= nums[each]        return result
reverseString

Core: Serializing String Value, then descending the list

class Solution(object):    def reverseString(self, s):        lst = []        for i in range(len(s)):            lst.append(s[-(i + 1)])        lst = ‘‘.join(lst)        return lst
Nim GAME

Core: Second player only win when  total accoumt % 4 = 0

class Solution(object):    def canWinNim(self, n):        val = n % 4        if val != 0:            return True        else:            return False
Counting Bits

Core: 

Each time the value is 2^n
The different between the the first half and second half is only the first digit

Example with 7
0 to 7 is
000

----
001

----
010
011

----

100
101
110
111
The Second half is always "1+Second Half

class Solution(object):    def countBits(self, num):        val = [0]        while len(val) <= num:            val += [i + 1 for i in val]        return val[:num + 1]
 
Sum of two integers

Core: Implementation of an array of Full Adder

 
class Solution(object):    def half_adder(self, a, b):        s = a ^ b        cin = a & b        return s, cin    def full_adder(self, a, b, cin):        s1, c1 = self.half_adder(a, b)        s2, c2 = self.half_adder(cin, s1)        c_out = c1 | c2        return s2, c_out    def getSum(self, a, b):        mask = 1        ci = 0        sum_total = 0        while mask <= 0x080000000:            a1 = a & mask            b1 = b & mask            (s, ci) = self.full_adder(a1, b1, ci)            sum_total = sum_total | s            ci <<= 1            mask <<= 1            print "s: " + str(s) + "     ci: " + str(ci)        maximum = 0x7FFFFFFF        mask = 0xFFFFFFFF        if sum_total > maximum:            sum_total = ~(sum_total ^ mask)        return sum_total
 

 

 

Personal Leetcode solution(Python)