Problem
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.
Solution//#1 public class Solution { /** * @param n: an unsigned integer * @return: the number of a€?1" bits */ public int hammingWeight(int n) { // write your code here int count = 0; while (n != 0) { n &= n-1; count++; } return count; } } //#2 public class Solution { /** * @param n: an unsigned integer * @return: the number of a€?1" bits */ public int hammingWeight(int n) { // write your code here int count = 0; while (n != 0) { count += (n&1); n = n>>>1; //unsigned bit right shift } return count; } } //#3 public class Solution { /** * @param n: an unsigned integer * @return: the number of a€?1" bits */ public int hammingWeight(int n) { // write your code here int count = 0; for (int i = 0; i < 32; i++) { if ((n & (1<
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.specialneedsforspecialkids.com/yun/71235.html
摘要:依次移位復(fù)雜度思路依次移動(dòng)位數(shù)進(jìn)行計(jì)算。代碼利用性質(zhì)復(fù)雜度,思路代碼 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). Fo...
摘要:在線網(wǎng)站地址我的微信公眾號(hào)完整題目列表從年月日起,每天更新一題,順序從易到難,目前已更新個(gè)題。這是項(xiàng)目地址歡迎一起交流學(xué)習(xí)。 這篇文章記錄我練習(xí)的 LeetCode 題目,語言 JavaScript。 在線網(wǎng)站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公眾號(hào): showImg(htt...
摘要:微信公眾號(hào)記錄截圖記錄截圖目前關(guān)于這塊算法與數(shù)據(jù)結(jié)構(gòu)的安排前。已攻略返回目錄目前已攻略篇文章。會(huì)根據(jù)題解以及留言內(nèi)容,進(jìn)行補(bǔ)充,并添加上提供題解的小伙伴的昵稱和地址。本許可協(xié)議授權(quán)之外的使用權(quán)限可以從處獲得。 Create by jsliang on 2019-07-15 11:54:45 Recently revised in 2019-07-15 15:25:25 一 目錄 不...
摘要:月下半旬攻略道題,目前已攻略題。目前簡(jiǎn)單難度攻略已經(jīng)到題,所以后面會(huì)調(diào)整自己,在刷算法與數(shù)據(jù)結(jié)構(gòu)的同時(shí),攻略中等難度的題目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道題,目前已攻略 100 題。 一 目錄 不折騰的前端,和咸魚有什么區(qū)別...
摘要:重復(fù)此步驟直到原數(shù)歸零。注意右移運(yùn)算符是算術(shù)右移,如果符號(hào)位是的話最高位將補(bǔ),符號(hào)位是的話最高位補(bǔ)。當(dāng)原數(shù)不為時(shí),將原數(shù)與上原數(shù)減一的值賦給原數(shù)。因?yàn)槊看螠p一再相與實(shí)際上是將最左邊的給消去了,所以消去幾次就有幾個(gè)。 Number of 1 Bits Write a function that takes an unsigned integer and returns the numbe...
閱讀 2035·2021-10-09 09:41
閱讀 1606·2021-09-28 09:36
閱讀 1113·2021-09-26 09:55
閱讀 1301·2021-09-10 11:17
閱讀 1155·2021-09-02 09:56
閱讀 2769·2019-08-30 12:58
閱讀 2939·2019-08-29 13:03
閱讀 1865·2019-08-26 13:40