您的位置:首页 > 编程语言 > C语言/C++

LeetCode 1: Number of 1 Bits (C++)

2016-01-23 17:17 417 查看
代码格式

•LeetCode不允许自己定义函数,只需要实现给定的函数即可。

•不需要定义main()函数,否则会编译通不过。

•如果需要有输出,直接return就行。我在第一题中使用了cout,就通不过。

题目描述

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as theHamming weight).

For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

解题思路

本题就是求一个无符号整数中1的个数,首先想到的是直接数,我的第一思路就是如此。还有一种方法就是使用技巧:n&(n-1)。

解法1:计数整数中的1。

#include<iostream>
using namespace std;
class Solution
{
public:
int hammingWeight(uint32_t n)
{
int count=0;
for(int i=0;i<32;i++)
{
if (n&(1<<i)) coun0t++;//如果出现1就给计数器加一
}
return count;
}
};


解法二:n&(n-1)可以将n的二进制表示的末尾1变成0,如果n末尾是0,则仍然是0.

class Solution {
public:
int hammingWeight(uint32_t n) {
int count=0;
while(n)//如果n的末尾(至少是末尾)有1则将其去掉,并计数。
{
n&=n-1;
count++;
}
return count;
}
};


另外:n&-n可以保留末尾的0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode