刷题的日常[Leetcode]——461)Hamming Distance and 476)Number complement

都是十进制和二进制的转换

461)

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        count=0
        a=[]
        shang,yushu=divmod(x,2)
        while shang!=0:
        	a.append(yushu)
        	shang,yushu=divmod(shang,2)
        a.append(yushu)
        b=[]
        shang,yushu=divmod(y,2)
        while shang!=0:
        	b.append(yushu)
        	shang,yushu=divmod(shang,2)
        b.append(yushu)
        l1=len(a)
        l2=len(b)
        if l1<l2:
        	t=l1
        	while t<l2:
        		a.append(0)
        		t+=1
        elif l1>l2:
        	t=l2
        	while t<l1:
        		b.append(0)
        		t+=1
        l=len(a)-1
        while l>=0:
        	if a[l]!=b[l]:
        		count+=1
        	l=l-1
        return count
if __name__=="__main__":
	sol=Solution()
	print sol.hammingDistance(4,1)

476)

class Solution(object):
    def findComplement(self, num):
        """
        :type num: int
        :rtype: int
        """
        a=[]
        b=[]
        shang,yushu=divmod(num,2)
        while shang!=0:
        	a.append(yushu)
        	shang,yushu=divmod(shang,2)
        a.append(yushu)
        i=len(a)-1
        j=0
        while i>=0:
        	if a[i]==1:
        		b.append(0)
        	else:
        		b.append(1)
        	j+=1
        	i=i-1
        res=0
        i=0
        while i<len(b):
        	zhishu=2**(len(b)-1-i)
        	res+=b[i]*zhishu
        	i=i+1
        return res
if __name__=="__main__":
	sol=Solution()
	print sol.findComplement(5)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值