当前位置:网站首页>Sword finger offer | number of 1 in binary
Sword finger offer | number of 1 in binary
2022-07-25 15:53:00 【Little Yapi】
Enter an integer n , Output the number 32 In bit binary representation 1 The number of . Negative numbers are represented by complements .
Method 1:
Method 1: take 32 Every one is associated with 1 Meet each other . Statistics 1 The number of .
public int NumberOf1(int n) {
int cnt = 0;
// Method 1: take 32 Every one is associated with 1 Meet each other . Statistics 1 The number of .
// 1 Of 32 Base number : 0000...1 1<<i: By gradually moving left , bring 1 Can and n Every phase of is related to
for(int i=0;i<32;i++){
if((n & (1<<i)) != 0){
cnt++;
}
}
return cnt;
}
Method 2:
Method 2: Gradually n On the right side of the 1 Turn into 0.
public int twoNumberOf1(int n) {
int cnt = 0;
// Method 2: Gradually n On the right side of the 1 Turn into 0.
// n = n & (n-1); take n The most the right side 1 Turn into 0
while (n != 0){
cnt ++;
n = n & (n-1);
}
return cnt;
}
Method 3:
Method 3: The digital n Turn into 32 Bit string form .
public int threeNumberOf1(int n) {
int cnt = 0;
// Method 3: The digital n Turn into 32 Bit string form .
String numStr = Integer.toBinaryString(n);
for(int i=0;i<numStr.length();i++){
if(numStr.charAt(i)=='1'){
cnt++;
}
}
return cnt;
}
边栏推荐
猜你喜欢

How matlab produces random complex sequences

通用测试用例写作规范

LeetCode - 641 设计循环双端队列(设计)*

Storage structure of cross linked list

Leetcode - 707 design linked list (Design)

华为2023届提前批预热开始!左 神的程序代码面试指南终派上用场

Pytorch学习笔记-Advanced_CNN(Using Inception_Module)实现Mnist数据集分类-(注释及结果)

LeetCode - 380 O(1) 时间插入、删除和获取随机元素 (设计 哈希表+数组)

Understanding the difference between wait() and sleep()

Leetcode - 359 log rate limiter (Design)
随机推荐
Pytorch学习笔记--常用函数总结3
对this对象的理解
Idea - click the file code to automatically synchronize with the directory
2019 Shaanxi Provincial race K-variant Dijstra
Matlab randInt, matlab randInt function usage "recommended collection"
Phased summary of the research and development of the "library management system -" borrowing and returning "module
Pat grade a 1153 decode registration card of PAT (25 points)
Hdu3873 shortest path with dependency (topological sorting)
Leetcode - 232 realize queue with stack (design double stack to realize queue)
Geogle Colab笔记1--运行Geogle云端硬盘上的.py文件
2021 Jiangsu race a Array line segment tree, maintain value range, Euler power reduction
IDEA—点击文件代码与目录自动同步对应
MySQL—用户和权限管控
< stack simulation recursion >
Understand "average load"
一文入门Redis
Geogle colab notes 1-- run the.Py file on the cloud hard disk of Geogle
MySQL教程65-MySQL操作表中数据
2021 Shanghai sai-d-cartland number variant, DP
2600 pages in total! Another divine interview manual is available~