11 二進制中1的個數

題目描述

輸入一個整數,輸出該數32位二進制表示中1的個數。其中負數用補碼錶示。

因爲golang的int是無限精度的,c++的int是32位的,所以golang的負數相當於前面有無限個1,要對golang的負數做處理.

func NumberOf1( n int ) int {
    // write code here
    cnt := 0
    if n < 0 {
        n = n & 0xffffffff
    }
    for n != 0 {
        n = n & (n - 1)
        cnt++
    }
    return cnt
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章