C++實現(xiàn)LeetCode(191.位1的個數(shù))
[LeetCode] 191.Number of 1 Bits 位1的個數(shù)
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.
很簡單的一道位操作Bit Manipulation的題,最近新出的三道題都沒有啥難度啊,這樣會誤導(dǎo)新人的,做了這三道得出個LeetCode沒啥難度的結(jié)論,其實里面好題真的不少,難題也很多,經(jīng)典題也多,反正就是贊贊贊,32個贊。
class Solution { public: int hammingWeight(uint32_t n) { int res = 0; for (int i = 0; i < 32; ++i) { res += (n & 1); n = n >> 1; } return res; } };
到此這篇關(guān)于C++實現(xiàn)LeetCode(191.位1的個數(shù))的文章就介紹到這了,更多相關(guān)C++實現(xiàn)位1的個數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
tinyxml 常用的C++ XML解析器非常優(yōu)秀
讀取和設(shè)置xml配置文件是最常用的操作,試用了幾個C++的XML解析器,個人感覺TinyXML是使用起來最舒服的,因為它的API接口和Java的十分類似,面向?qū)ο笮院芎?/div> 2012-11-11C語言中g(shù)etchar(?)?函數(shù)使用詳解
getchar()?字符輸入函數(shù),沒有參數(shù),從輸入緩沖區(qū)里面讀取一個字,需要注意一次只能讀取一個字符,這篇文章主要介紹了C語言中g(shù)etchar函數(shù)使用詳解,需要的朋友可以參考下2022-12-12最新評論