LeetCode -- Number of 1 Bits

原创 2015年11月21日 10:24:34
题目描述:


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的个数。


思路:
对于整数n,从n开始对n和n-1做与运算然后赋值给n。即,n=n&n-1。直到n等于n为止。能做多少次运算就说明有多少个1。


实现代码:

public class Solution {
    public int HammingWeight(uint n) {
        int count;
		for (count=0; n > 0 ; count++){
			n &= n-1;
		}
		return count;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

【LeetCode】Number of 1 Bits 解题报告

Number of 1 Bits[LeetCode]https://leetcode.com/problems/number-of-1-bits/Total Accepted: 88721 Total...

LeetCode 191. Number of 1 Bits

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

一、题目描述 Write a function that takes an unsigned integer and returns the number of ’1' bits it ha...

Leetcode 191 Number of 1 Bits

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

题目链接:https://leetcode.com/problems/number-of-1-bits/     题目内容: Write a function that takes an unsi...

leetcode笔记:Number of 1 Bits

题目的要求很简单,找出一个整数对应的二进制格式中有多少个'1'。

LeetCode------Number of 1 Bits

题目简介 Write a function that takes an unsigned integer and returns the number of ’1' bits it has (als...

LeetCode题解:number-of-1-bits

在云南出差的时候我开始刷LeetCode上的 算法题了,一共一百八十多道题,不知道 我得做到什么时候。好了闲话不多说,先 来对我做出的第一道题写个报告: 题目链接: 点击打开链接number...
  • yums467
  • yums467
  • 2015年03月26日 15:07
  • 358

LeetCode-Number of 1 Bits

Question Write a function that takes an unsigned integer and returns the number of ’1’ bits it has...

[LeetCode]Number of 1 Bits

QuestionWrite a function that takes an unsigned integer and returns the number of ’1’ bits it has (a...
  • byamao1
  • byamao1
  • 2016年12月13日 22:19
  • 83
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode -- Number of 1 Bits
举报原因:
原因补充:

(最多只允许输入30个字)