Leetcode 挑战 Day 08 [191. Number of 1 Bits]

191. 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).

Example 1:

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:

Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:

Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

这题的题目是希望我们算出题目所给的整数,以二进位表示的话,会出现多少个一。

Decimal to Binary


如何从十进位转换成二进位?我们在现实生活上,实际可以透过短除法不断除二,如果有余数1的那栏位就填1,没有就填写0,直到最後出现被除数变为零。
而在程序上我们可以透过以下的程序码来呈现上述的想法,通过回圈,取余数,除以二(取整数),不断重复做,如果取余数不为零,就在变数ans加一,如此一来我们便可以知道一个十进位的数字中有多少个一了。

以下为python3的程序码

class Solution:
    def hammingWeight(self, n: int) -> int:
        ans = 0
        while n>0:
            if n % 2 != 0:  # 也可以写成 ans += n % 2
                ans += 1 
            n = n // 2   # n //= 2
        return ans

Bit shiftting


除了上述直观的想法,我们也可以用更接近电脑语言的方式,那便是通过对题目给我们的数字不断往右shift,与1做&逻辑运算,这样一来我们可以得知,只有出现1的地方与1做&运算才会是1,这麽一来,我们也能算出来有多少个1。

以下是python3的程序码

class Solution:
    def hammingWeight(self, n: int) -> int:
        ans = 0
        while n > 0:
            if (1 & n):  # AND逻辑运算
                ans += 1
            n >>= 1  # 往右Shift
        return ans

以下是C++的程序码

class Solution {
public:
    int hammingWeight(uint32_t n) 
{
	int ans = 0;
	while(n > 0)
	{
		if(n & 1UL)
			ans++;
		n >>= 1;
	}
	return count;
}
};

<<:  把问题界定清楚,远比提出解决方案更为重要。

>>:  [Day11] 设定 DialogFlow 专案

DAY28 linebot message api-Template 介绍-1

传送样板(Template) 样板有四种,分别是 Confirm、Buttons、Carousel、...

利用Redlock演算法实现自己的分布式锁

前言 我之前有写透过 lock or CAS 来防治,Racing condition 问题,但如果...

Day22 xib传值的小教室3

接续昨天~ 我们就先展示将第一页值是第二页的成果吧! 按下按钮後! 这样就完成罗! 但是我们如果想将...

倒计时按钮文字闪烁问题

缘由: UIUX提出一个新功能,要在按钮上加上倒数秒数,这个功能算是常见,但开始动手作完了之後,问题...

AE火焰练习-Day15

六指渊参考范例:https://www.sixvfx.com/ae_combustion 竟然来到第...