在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight). Example 1: Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string
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:
Follow up: If this function is called many times, how would you optimize it? 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 示例 1: 输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串
示例 2: 输入:00000000000000000000000010000000 输出:1 解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。 示例 3: 输入:11111111111111111111111111111101 输出:31 解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。 提示:
进阶: 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 }
|
请发表评论