leetcode Day3 complement number 【补码】

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:


The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.

Example 1:
 
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

解决方法:
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
result=[]
while num!=0:
remainder=num%2
num=num/2
result.append(remainder)
l=len(result)

for i in range(l/2):
temp=result[i]
result[i]=result[l-i-1]
result[l-i-1]=temp
lam=lambda x:abs(x-1)

for i in range(l):
result[i]=lam(result[i])

#print result
sum=0
for i in range(l):
sum=sum+result[l-i-1]*pow(2,i)
return sum

PS: 上面的方法是第一次开始做的最原始的方法,巨傻无比。 完全就是一个没学过计算机原理或者微机原理的人的代码哈。 连一个数的补码这种计算机第一节课的内容都还给老师了。。
 
附上最简便的一个解法:
class Solution(object):
def findComplement(self, num):
i = 1
while i <= num:
i = i << 1
return (i - 1) ^ num

以为其实一个补码就是一个数与另外一个全1的数进行异或处理哈。
鄙视自己!!!
 
 

0 个评论

要回复文章请先登录注册