Leetcode: Number of 1 Bits
LeetCode of number Bits
2023-09-11 14:14:07 时间
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.
注意两点:1. 我用的 rightshift 是>>>, 是unsigned right shift
2. & 的优先级不如 ==, 所以要把&的两个参数括起来
1 public class Solution { 2 // you need to treat n as an unsigned value 3 public int hammingWeight(int n) { 4 int count = 0; 5 for (int i=0; i<32; i++) { 6 if ((n>>>i & 1) == 1) count++; 7 } 8 return count; 9 } 10 }
相关文章
- Java实现 LeetCode 816 模糊坐标(暴力)
- Java实现 LeetCode 153 寻找旋转排序数组中的最小值
- Java实现 LeetCode 59 螺旋矩阵 II
- Java实现LeetCode_0028_ImplementStrStr
- LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- [LeetCode] Reverse Vowels of a String
- [LeetCode] Power of Three | Power of Two
- leetcode 17. 电话号码的字母组合----回溯算法
- LeetCode - 402 移掉 K 位数字
- 成功解决ValueError: Number of passed names did not match number of header fields in the file
- Leetcode 507. 完美数(可以,已解决)
- Leetcode 1089. 复写零
- Leetcode 594. 最长和谐子序列(已解决)
- [LeetCode] 201. Bitwise AND of Numbers Range ☆☆☆(数字范围按位与)
- leetcode 17 -- Letter Combinations of a Phone Number
- LeetCode Median of Two Sorted Arrays
- 力扣LeetCode,两个数组的交集
- 【LeetCode】【Python题解】Single Number & Maximum Depth of Binary Tree
- leetcode 559. Maximum Depth of N-ary Tree
- leetcode 191. Number of 1 Bits
- leetcode 628. Maximum Product of Three Numbers
- leetcode 371. Sum of Two Integers
- leetcode 104. Maximum Depth of Binary Tree
- leetcode 762. Prime Number of Set Bits in Binary Representation
- 【Leetcode刷题Python】42. 接雨水