leetcode 191. Number of 1 Bits 位1的个数(简单)
一、题目大意
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
提示:
请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。
示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。
示例 2:
输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 ‘1’。
示例 3:
输入:11111111111111111111111111111101
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 ‘1’。
提示:
- 输入必须是长度为 32 的 二进制串 。
进阶:
- 如果多次调用这个函数,你将如何优化你的算法?
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-1-bits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题思路
思路1:n & 1如果为1,ans=ans+1,然后再n向右移一位,直到n=0,返回ans。注意:因为是Java实现所以要用for
思路2:先判断如果n!=0,ans++,令n = n&(n-1),循环直到n=0,返回ans。参考别人的思路,没看懂
三、解题方法
3.1 Java实现 - 思路1
public class Solution2 {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ans = 0;
for (int i = 0; i < 32; i++) {
ans += n & 1;
n >>= 1;
}
return ans;
}
}
3.2 Java实现 - 思路2
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ans = 0;
while (n != 0) {
ans++;
n = n & (n - 1);
}
return ans;
}
}
四、总结小记
- 2011/10/24 有些东西想不明白,就埋藏心底,发酵一会
相关文章
- LeetCode 评论区:你管这难度叫简单???
- Leetcode: Wiggle Sort
- Leetcode: Validate Binary Search Tree
- Leetcode: Minimum Window Substring
- Leetcode: Convert Sorted List to Binary Search Tree
- 【Leetcode】101. 对称二叉树(简单)
- 【Leetcode】21. 合并两个有序链表(简单)
- leetcode 精选100题(7)合并二叉树-简单
- JS LeetCode 303. 区域和检索 - 数组不可变,一维数组的前缀和
- JS LeetCode 1423. 可获得的最大点数简单题解
- [LeetCode]面试题 16.11. 跳水板
- LeetCode数据结构_C语言题解系列-数组II&动态规划
- 【LeetCode】223. Rectangle Area
- 【LeetCode】8. String to Integer (atoi)
- LeetCode 137 Single Number II(仅仅出现一次的数字 II)(*)
- [LeetCode] 1019. Next Greater Node In Linked List 链表中的下一个较大的结点
- [LeetCode] 685. Redundant Connection II 冗余的连接之二
- [LeetCode] 659. Split Array into Consecutive Subsequences 将数组分割成连续子序列
- [LeetCode] 159. Longest Substring with At Most Two Distinct Characters 最多有两个不同字符的最长子串
- 【LeetCode】146. LRU缓存机制
- Leetcode——69. Sqrt(x)
- leetcode 146. LRU Cache LRU 缓存 (简单)
- leetcode 530. Minimum Absolute Difference in BST二叉搜索树的最小绝对差 (简单)
- leetcode 617. Merge Two Binary Trees 合并二叉树(简单)
- leetcode 669. Trim a Binary Search Tree 修剪二叉搜索树 (简单)
- leetcode 114. Flatten Binary Tree to Linked List 二叉树展开为链表(简单)
- leetcode 69. Sqrt(x) x 的平方根(简单)
- leetcode算法108.将有序数组转换为二叉搜索树