leetcode之Counting Bits
2016-06-18 01:23
369 查看
这题是用来找出来一个数字化为2进制是有多少个1的,题目的提示很明显,就是要去找规律。规律其实很简单。就是2的n次方之后的都是1-2的n次方-1的值再加上1。难得写个能打败90%多的解。
class Solution(object): def countBits(self, num): """ :type num: int :rtype: List[int] """ if num == 0: return [0] if num == 1: return [0, 1] if num == 2: return [0, 1, 1] number = 1 list1 = [0, 1, 1] for i in xrange(3, num + 1): if i & (i - 1) == 0: list1.append(1) number += 1 else: list1.append(list1[i - 2 ** number] + 1) return list1
相关文章推荐
- Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)
- 详解Android应用中屏幕尺寸的获取及dp和px值的转换
- 基于Android中dp和px之间进行转换的实现代码
- Android中dip、dp、sp、pt和px的区别详解
- LFC1.0.0 版本发布
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- Android dpi,dip,dp的概念以及屏幕适配
- Android px、dp、sp之间相互转换
- HP data protector软件学习1--基本角色与基本工作流程
- HP data protector软件学习2--软件组成与界面介绍
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays