iT邦幫忙

2023 iThome 鐵人賽

DAY 30
0
自我挑戰組

30天leetcode學習旅程系列 第 30

項次 30 - Bit Operations

  • 分享至 

  • xImage
  •  

題目:191. Number of 1 Bits

連結:https://leetcode.com/problems/number-of-1-bits/description/

  • 等級:Easy
class Solution {
    public int hammingWeight(int n) {
        
        int count = 0;

        while (n != 0) {
            
            if ((n & 1) == 1)
                count++;
            
            n = n >>> 1;
        }
            
        return count;
    }
}
  • Time complexity: O(n)
  • Space complexity: O(1)

題目:190. Reverse Bits

連結:https://leetcode.com/problems/reverse-bits/description/

  • 等級:Easy
  • The input must be a binary string of length 32
class Solution {
    
    public int reverseBits(int num) {
        
        num = ((num & 0xffff0000) >>> 16) | ((num & 0x0000ffff) << 16);
        num = ((num & 0xff00ff00) >>> 8) | ((num & 0x00ff00ff) << 8);
        num = ((num & 0xf0f0f0f0) >>> 4) | ((num & 0x0f0f0f0f) << 4);
        num = ((num & 0xcccccccc) >>> 2) | ((num & 0x33333333) << 2);
        num = ((num & 0xaaaaaaaa) >>> 1) | ((num & 0x55555555) << 1);
        
        return num;
        
    }
}
  • Time complexity: O(1)
  • Space complexity: O(1)

上一篇
項次 29 - 2-Dimension DP
系列文
30天leetcode學習旅程30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言