LeetCode Number of 1 Bits JAVA
来源:互联网 发布:童装淘宝店名大全 编辑:程序博客网 时间:2024/06/14 18:30
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.
先是考虑之前学到的汉明码,写了下面这个算法:
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int num = 0; if(n==0){ return 0; } while(n/2 != 0){ num = num + n%2; n = n/2; } return num+1; }}自己调试了一下,好像也没什么问题。提交代码答案的时候,发现出错了。搞半天是题目说的意思是用unsigned int类型。这样,当输入的范围超过int最大值2的32次方以后,就会出现问题了。
后来考虑了一下,这题目比较简单的方法还是使用位运算符比较容易实现。
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int count = 0; for (int i=0; i<32; i++) { if ((n>>>i & 1) == 1)
<span style="white-space:pre"></span>count++; } return count; } }
0 0
- [LeetCode][Java] Number of 1 Bits
- LeetCode|Number of 1 Bits-java
- (java)leetcode Number of 1 Bits
- Leetcode: 191. Number of 1 Bits(JAVA)
- LeetCode Number of 1 Bits JAVA
- LeetCode 191 -Number of 1 Bits ( JAVA )
- leetcode:bits:Number of 1 Bits(191)
- LeetCode:Number of 1 Bits
- LeetCode-Number of 1 Bits
- leetcode: Number of 1 Bits
- LeetCode Number of 1 Bits
- Leetcode: Number of 1 Bits
- Leetcode--Number of 1 Bits
- [LeetCode] Number of 1 Bits
- [leetcode]Number of 1 Bits
- Leetcode-Number of 1 Bits
- LeetCode Number of 1 Bits
- LeetCode-Number of 1 Bits
- codeforces 555c 数据结构(map 的使用)
- 初试牛客网PAT练习之数素数
- HTML5实现全屏API【进入和退出全屏】
- AndroidStudio配置NDK开发环境
- leetcode--- Symmetric Tree---平衡二叉树
- LeetCode Number of 1 Bits JAVA
- MySQL基本概述
- Mysql中事务隔离级详解
- bootstrap, boosting, bagging 几种方法的联系
- Ubuntu下安装Tomcat
- 深入理解JVM—JVM内存模型
- if循环
- hexo安装教程
- Stegano之StegSolve、StegDetect、InvisibleSecrets