0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LeetCode - 191. Number of 1 Bits

Last updated at Posted at 2020-01-29

191. Number of 1 Bits

今日は超軽いやつ。

解答


# @param {Integer} n, a positive integer
# @return {Integer}
def hamming_weight(n)
  n.to_s(2).scan(/1/).size
end

メモ

テストしようと思って以下のようにやってしまい、しばらく首を傾げてしまった。この入力値だと8進数だととられる


hamming_weight(00000000000000000000000000001011)

やるなら 0b をつけて、こうしないと。これで二進数と思ってくれる。


hamming_weight(0b00000000000000000000000000001011)

sprintf あたりが参考になる

スコア


Runtime: 28 ms, faster than 90.28% of Ruby online submissions for Number of 1 Bits.
Memory Usage: 9.3 MB, less than 100.00% of Ruby online submissions for Number of 1 Bits.

おっ、なかなかいいのでは。

シリーズ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?