概述
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
最后
以上就是幸福钢笔为你收集整理的Leetcode--两道简单的二进制问题的全部内容,希望文章能够帮你解决Leetcode--两道简单的二进制问题所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复