本文主要是介绍LeetCode-Number_of_1_Bits,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目: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‘的函数(也称作海明重量)。
举例,32位的数字’11‘用二进制表示为00000000000000000000000000001011,因此,编写的函数应该返回3。
思路:
很容易想到用位移来判断输入n的每一位是否为1,不断向右位移和‘&1’(‘与’)操作。位移是为了将n的每一位都移到最后一位,从而进行‘与1’操作,而’&1‘操作是为了判断移到最后的这一位是否为1。若‘&1’后得1,则n的最后一位为1,result(输出)‘+1’,否则,那么n的最后一位为0,result不做处理。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;class Solution {
public:int hammingWeight(uint32_t n) {int result = 0;for (int i = 0; i < 32; i++) {if (n & 1 == 1) {result ++ ;}n = n >> 1;}return result;}
};int main()
{Solution s;uint32_t n=11;int result;result = s.hammingWeight(n);cout << result;return 0;
}
这篇关于LeetCode-Number_of_1_Bits的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!