LeetCode Number of 1 Bits 计算1的个数
题意:
提供一个无符号32位整型uint32_t变量n,返回其二进制形式的1的个数。
思路:
考察二进制的特性,设有k个1,则复杂度为O(k)。考虑将当前的数n和n-1做按位与,就会将n的最后一个1去掉,重复这样的操作就可以统计出1的个数了。(2015年春季 小米实习生的笔试题之一)
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt=;
while(n)
{
n&=n-;
cnt++;
}
return cnt;
}
};
AC代码
python3
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
cnt=0
while n:
cnt+=1
n=n&(n-1)
return cnt
AC代码
LeetCode Number of 1 Bits 计算1的个数的更多相关文章
- [LeetCode] Number of 1 Bits 位1的个数
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know ...
- 2016.5.15——leetcode:Number of 1 Bits ,
leetcode:Number of 1 Bits 代码均测试通过! 1.Number of 1 Bits 本题收获: 1.Hamming weight:即二进制中1的个数 2.n &= (n ...
- LeetCode Number of 1 Bits
原题链接在这里:https://leetcode.com/problems/number-of-1-bits/ 题目: Write a function that takes an unsigned ...
- [LeetCode] 191. Number of 1 Bits 二进制数1的个数
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know ...
- [LeetCode] 191. Number of 1 Bits ☆(位 1 的个数)
描述 Write a function that takes an unsigned integer and return the number of '1' bits it has (also kn ...
- [LeetCode] Number of 1 Bits 位操作
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know ...
- [LeetCode] Number of Digit One 数字1的个数
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less th ...
- LeetCode——Number of 1 Bits
//求一个整数的二进制串中1的个数 public int hammingWeight(int n) { String b_str = Integer.toBinaryString(n); int b_ ...
- [LeetCode] Number of Distinct Islands 不同岛屿的个数
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) conn ...
随机推荐
- 项目中缺少org.wltea.ik-analyzer如何解决?
IKAnalyzer是一个开源的,基于java语言开发的轻量级的中文分词工具包.从2006年12月推出1.0版开始,IKAnalyzer已经推出了3个大版本.最初,它是以开源项目Luence为应用主体 ...
- C# 写 LeetCode Medium #2 Add Two Numbers
2. Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. ...
- 微信小程序-获取当前城市位置
CSDN链接 https://blog.csdn.net/weixin_42262436/article/details/80458430
- C++开源库(一) ----log4cpp详解
我们在写程序的时候通常会希望将一些信息记录下来,方便我们进行日后的一些信息跟踪,错误排查等等.比如:我们在进行数据库操作的时候,我们通常希望知道现在是程序的哪一部分进行了数据库的操作,所以我们会记录下 ...
- Python中的循环语句
Python中有while循环和for循环 下面以一个小例子来说明一下用法,用户输入一些数字,输出这些数字中的最大值和最小值 array = [5,4,3,1] for i in array: pri ...
- LibreOJ #6192. 「美团 CodeM 复赛」城市网络
#6192. 「美团 CodeM 复赛」城市网络 内存限制:64 MiB时间限制:500 ms标准输入输出 题目类型:传统评测方式:文本比较 上传者: sqc 提交提交记录统计讨论测试数据 题目描 ...
- ES6扩展运算符...进行的数组删除
今天写了按照React小书写了Reducer,发现基础真是太重要了,所有关于上层建筑的细节都需要回到下层细节中去寻找,而且现在的基础也由ES3变成了ES6了. const ADD_USER = &qu ...
- Windows 新增 Sublime Text3 右键快捷方式
Win10 创建 Sublime Text 3 右键快捷方式 Windows + R 输入 regedit 打开注册表编辑器: 依次找到 计算机\HKEY_CLASSES_ROOT\*\shell: ...
- learn_tmp
// 4.1构造映射val scores = Map("Alice" -> 10, "Bob" -> 3, "Cindy" -& ...
- spark_learn
package chapter03 import org.apache.spark.sql.DataFrame import org.apache.spark.sql.hive.HiveContext ...