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

来源:互联网 发布:雅马哈p115软件 编辑:程序博客网 时间:2024/06/05 01:57

代码格式
•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

0 0