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
so the function should return 3.【对于一个32位无符号数整数返回它的的二进制表示形式中的1的个数】
Python解决方案:
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解决方案:
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】碰到一道脑残leetcode,比之前觉得简单的还简单。。。一下还两道……Search in Rotated Sorted Array I和II
- 还是二进制的技巧问题;简单记录一下;
- LeetCode | 762. Prime Number of Set Bits in Binary Representation 简单题 二进制技巧题
- 贡献两道简单的leetcode
- leetcode简单题目两道(4)
- leetcode简单题目两道(3)
- leetcode 455. Assign Cookies 饼干满足问题 + 一个简单的归并过程
- LeetCode-Decode Ways-编码方式-简单DP计数问题
- leetcode简单题目两道(2)
- 【LeetCode111-120】很多道二叉树的问题(左右顺序很重要),一道hard DP题,两道杨辉三角以及一道DP三角
- leetcode 两道交换问题
- leetcode 115. Distinct Subsequences 简单DP变形+一个必须要学会的DP问题
- 【Leetcode】二叉树简单路径最大和问题
- 【LeetCode】三道简单的递归问题
- leetcode 438. Find All Anagrams in a String 一个简单的移动窗口问题
- LeetCode | 746. Min Cost Climbing Stairs | 简单DP上楼梯问题
- leetcode简单题目两道(5)
- 简单问题,解决了也开心
- JAVA学习中应该注意的一些简单问题?