您的位置:首页 > 其它

Leetcode--两道简单的二进制问题

2015-04-06 21:36 351 查看
Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011
,
so the function should return 3.【对于一个32位无符号数整数返回它的的二进制表示形式中的1的个数】

Python解决方案:
class Solution:
def hammingWeight(self, n):
if n == 0:
return 0
i = 0
while (n!=0 ):
if n==1:
return i+1
if n%2 == 1:
i=i+1
n = (n-n%2)/2
return i


Reverse Bits:

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary
as00111001011110000010100101000000).【将一个32位无符号数的二进制表示形式(前面补0使其长度为32位)倒叙,然后转换为十进制】

Python解决方案:
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
if n==0:
return 0
str = "" #str存储着这个数的二进制形式的倒叙(没有补0时)
while(n!=0):
if n == 1:
str +="1"
break
if(n%2==0):
str +="0"
else:
str += "1"
n=(n-n%2)/2
result = 0
Flag = 32  #表示i在第几位
for i in str:
if i=="1":
result +=pow(2,Flag-1)
Flag = Flag-1
return result
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: