iT邦幫忙

2024 iThome 鐵人賽

DAY 13
0
佛心分享-刷題不只是刷題

C/C++ 刷題30天系列 第 13

Day13__C語言刷LeetCode

  • 分享至 

  • xImage
  •  

2980. Check if Bitwise OR Has Trailing Zeros

tags: Easy、Bitwise

You are given an array of positive integers nums.
You have to check if it is possible to select two or more elements in the array such that the bitwise OR of the selected elements has at least one trailing zero in its binary representation.
For example, the binary representation of 5, which is "101", does not have any trailing zeros, whereas the binary representation of 4, which is "100", has two trailing zeros.
Return true if it is possible to select two or more elements whose bitwise OR has trailing zeros, return false otherwise.

解法:

bool hasTrailingZeros(int* nums, int numsSize) {
    int even_count = 0;
    for (int i = 0; i < numsSize; i++) {
        if (nums[i] % 2 == 0) {
            even_count++;
        }
    }
    if (even_count >= 2) {
        return true;
    }
    else {
        return false;
    }
}

190. Reverse Bits

tags: Easy、Bitwise

Reverse bits of a given 32 bits unsigned integer.

解法1: 反轉

uint32_t reverseBits(uint32_t n) {
    uint32_t result = 0;
    for (int i = 0; i < 32; i++) {
        if ((n & (1U << i))) { //若n值的第i位元為1,則返回1
            result = result | (1U << ((32 - 1) - i));
        }
    }
    return result;
}

解法2:

uint32_t reverseBits(uint32_t n) {
    uint32_t result = 0;
    for (int i = 31; i >= 0; i--) {
        uint32_t bit = (n & 1) << i; //提取n的最低為原並將其放置反轉後的位置
        result |= bit;  //將該位元加入結果中
        n = n >> 1; //將n右移,準備處理下一個位元
    }
    return result;
}

上一篇
Day12__C語言刷LeetCode
下一篇
Day14__C語言刷LeetCode
系列文
C/C++ 刷題30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言