设为首页 加入收藏

TOP

LN : leetcode 191 Number of 1 Bits
2017-10-12 12:45:26 】 浏览:6204
Tags:leetcode 191 Number Bits

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

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

analysation

如果当前的数据为有符号数,在进行右移的时候,根据符号位决定左边补0还是补1。如果符号位为0,则左边补0;但是如果符号位为1,则根据不同的计算机系统,可能有不同的处理方式。
将所有对2的整除运算转换为位移运算,可提高程序的运行效率。

soliution

int hammingWeight(uint32_t n) {
  int t, sum = 0;
  for (t = 31; t >= 0; t--) {
      if ((n >> t & 1) == 1)
      sum++;
  }
  return sum;
}
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇7za 命令解析 下一篇LN : leetcode 242 Valid Anagram

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目