190.Reverse Bits
先转化为2进制,取[2:](排除0b),转换成列表,填充0,join,int转换
1 class Solution: 2 # @param n, an integer 3 # @return an integer 4 def reverseBits(self, n): 5 m = bin(n) 6 length = len(m) 7 t = 32 -length +2 8 m = list(m[2:]) 9 m.reverse() 10 q = m + ['0']*t 11 q = ''.join(q) 12 result = int(q,2) 13 return result
191.Number of 1 Bits
返回二进制中的1的数目
int数字转化为二进制字符串,转换成列表,迭代判断1。或者使用字符串方法count
1 class Solution(object): 2 def hammingWeight(self, n): 3 """ 4 :type n: int 5 :rtype: int 6 """ 7 return bin(n).count('1') 8 9 """ m = bin(n) 10 result = 0 11 for i in range(len(m)): 12 if m[i] == '1': 13 result +=1 14 15 return result"""
198. House Robber
动态规划思想。假设有i户,nums[i],max表示能得到的最多钱
1户人家:max[0]=nums[0]
2户人家:其中钱多的一家 max[1]=max(nums[0],nums[1])
3户人家:此时有两个选择,第一个不偷第三户人家:前两户人家中的最大值,第二个偷第三户人家:偷第一户和第三户
i户:同样 不偷:max[i-1],偷:max[i-2]+nums[i]
1 class Solution(object): 2 def rob(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 m = len(nums) 8 if m == 0: 9 return 0 10 if m == 1: 11 return nums[0] 12 dp = [0 for i in range(len(nums))] 13 dp[0] = nums[0] 14 dp[1] = max(nums[0],nums[1]) 15 for i in range(2,m): 16 dp[i] = max(dp[i-2]+nums[i],dp[i-1]) 17 18 return dp[i]