leetcode 191. 位1的个数(移位操作)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 191. 位1的个数(移位操作)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
題解
這個題,可以直接參考 190. 顛倒二進制位
public class Solution {// you need to treat n as an unsigned valuepublic int hammingWeight(int n) {int cnt = 0;for (int i = 0; i < 32; i++) {cnt += n >>> i & 1;System.out.println(n >>> i & 1); // 無符號右移}return cnt;} }評論區一些比較好的解法
Java API
public class Solution {// you need to treat n as an unsigned valuepublic int hammingWeight(int n) {return Integer.bitCount(n);} }總結
以上是生活随笔為你收集整理的leetcode 191. 位1的个数(移位操作)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 190. Revers
- 下一篇: leetcode 198. 打家劫舍(最