leetcode-191-Number of 1 Bits
生活随笔
收集整理的這篇文章主要介紹了
leetcode-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: 11 Output: 3 Explanation: Integer 11 has binary representation 00000000000000000000000000001011Example 2:
Input: 128 Output: 1 Explanation: Integer 128 has binary representation 00000000000000000000000010000000?
要完成的函數:
int hammingWeight(uint32_t n)?
?
說明:
1、這道題目給定一個數n,要求轉換為二進制之后,數一下有多少個1,輸出1的個數。
2、明白題意,這道題用位操作完成,十分容易。
代碼如下:(附詳解)
int hammingWeight(uint32_t n) {int res=0;for(int i=0;i<32;i++){res+=(n&1);//取出最后一位,如果是1那么加上去,如果是0加上去也一點影響都沒有,避開了條件判斷n>>=1;//n右移一位}return res;}上述代碼實測4ms,beats 100% of cpp submissions。
轉載于:https://www.cnblogs.com/chenjx85/p/9107743.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的leetcode-191-Number of 1 Bits的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Powershell 美化,Fluent
- 下一篇: ENVI5.3 辐射校正相关操作