码迷,mamicode.com
首页 > 编程语言 > 详细

Personal Leetcode solution(Python)

时间:2016-09-08 23:06:46      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

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)

标签:

原文地址:http://www.cnblogs.com/eli-ayase/p/5854762.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!