★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-yjjxofeu-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).git
Example 1:github
Input: 00000000000000000000000000001011 Output: 3 Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:算法
Input: 00000000000000000000000010000000 Output: 1 Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:微信
Input: 11111111111111111111111111111101 Output: 31 Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
Note:函數
-3
.Follow up:優化
If this function is called many times, how would you optimize it?this
編寫一個函數,輸入是一個無符號整數,返回其二進制表達式中數字位數爲 ‘1’ 的個數(也被稱爲漢明重量)。spa
示例 1:code
輸入:00000000000000000000000000001011 輸出:3 解釋:輸入的二進制串 00000000000000000000000000001011 中,共有三位爲 '1'。
示例 2:
輸入:00000000000000000000000010000000 輸出:1 解釋:輸入的二進制串 00000000000000000000000010000000 中,共有一位爲 '1'。
示例 3:
輸入:11111111111111111111111111111101 輸出:31 解釋:輸入的二進制串 11111111111111111111111111111101 中,共有 31 位爲 '1'。
提示:
-3
。進階:
若是屢次調用這個函數,你將如何優化你的算法?
12ms
1 class Solution { 2 func hammingWeight(_ n: UInt32) -> UInt32 { 3 var n = n 4 var res: UInt32 = 0 5 for i in 0..<32 6 { 7 res += (n & 1) 8 n = n >> 1 9 } 10 return res 11 } 12 }