From ff65ebea6fa9564c85bff0661629e4d306c0b6ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Tue, 23 Oct 2018 20:39:17 +0800 Subject: [PATCH] Create 191. Number of 1 Bits.md --- 191. Number of 1 Bits.md | 52 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 191. Number of 1 Bits.md diff --git a/191. Number of 1 Bits.md b/191. Number of 1 Bits.md new file mode 100644 index 0000000..25c300f --- /dev/null +++ b/191. Number of 1 Bits.md @@ -0,0 +1,52 @@ +# [191. Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/description/) +# 思路 +## 思路一 +不断循环,每次循环得到最低位的值,最后可得到所有位1的个数。怎样得到最低位的值,两种方法: +* 1、若num为奇数,则num的最低位肯定为1; +* 2、用一个只有低位是1的mask与num进行与操作即可得到最低位; +## 思路二* +依然是循环,但是每次循环不是得到最低位的值,而是每次循环去掉一个1,用一个count计数即可得到答案。 +# C++ +## 思路一 +``` +// 方法1 +class Solution { +public: + int hammingWeight(uint32_t n) { + int res = 0; + while(n != 0){ + res += (n % 2); + n /= 2; + } + return res; + } +}; + +// 方法2 +class Solution { +public: + int hammingWeight(uint32_t n) { + int res = 0; + uint32_t mask = 1; + for(int i = 0; i < 32; i++){ + res += (n & mask); + n = n >> 1; + } + return res; + } +}; +``` +## 思路二* +``` +class Solution { +public: + int hammingWeight(uint32_t n) { + int count = 0; + while (n) { + n &= (n - 1); // 去掉最后的1 + count++; + } + return count; + } +}; +```