1. 程式人生 > >python leetcode 136. Single Number 137. Single Number II

python leetcode 136. Single Number 137. Single Number II

136. Single Number

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res=0
        for n in nums:
            res ^= n 
        return res

137. Single Number II 想想Single Number是怎麼做。a^a=0的本質是a轉化為二進位制的a1,兩個a1每位上的數字對應相加取模2=0. 所以k次就轉為k進位制。這題是k=3,還要注意負數。

class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        self.r=[0]*32
        k=3
        for n in nums:
            if n<0: n+=2**32
            self.helper(n,k) 
        m=self.K_ten(self.r,k)
        return m if m<
2**31 else m-2**32 def helper(self,n,k): cur=self.ten_K(n,k) for i in range(32): self.r[i]=(self.r[i]+cur[i])%k def K_ten(self,n,k): res=0 for i in range(31,-1,-1): res=res*k+n[i] return res def ten_K(self,n,k): res=
[0]*32 index=0 while n: res[index]=n%k n//=k index+=1 return res