iT邦幫忙

2024 iThome 鐵人賽

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

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

Day15__C語言刷LeetCode

  • 分享至 

  • xImage
  •  

過了一半,該開始挑戰一天寫3題了~

693. Binary Number with Alternating Bits

tags: Easy、Bitwise

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

解法1:

bool hasAlternatingBits(int n) {
    int first = n & 1;
    n >>= 1;
    while (n != 0) {
        int second = n & 1;
        if (first == second) {
            return false;
        }
        first = second;
        n >>= 1;
    }
    return true;
    
}

解法2:

bool hasAlternatingBits(int n) {
    while (n != 0) {
        if ((n & 1) == ((n>>1) & 1)) {
            return false;
        }
        n >>= 1;
    }
    return true;
}

717. 1-bit and 2-bit Characters

tags: Easy、Bitwise

We have two special characters:
The first character can be represented by one bit 0.
The second character can be represented by two bits (10 or 11).
Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.

解法:

bool isOneBitCharacter(int* bits, int bitsSize) {
    int check = 0;
    while (check < bitsSize-1) {
        if (bits[check] == 1) {
            check += 2;
        }
        else {
            check++;
        }
    }
    if (check == bitsSize) {
        return false;
    }
    return true;
}

2220. Minimum Bit Flips to Convert Number

tags: Easy、Bitwise

A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0.
For example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110, flip the second bit from the right to get 101, flip the fifth bit from the right (a leading zero) to get 10111, etc.
Given two integers start and goal, return the minimum number of bit flips to convert start to goal.

解法:

int minBitFlips(int start, int goal) {
    int count = 0;
    while ((goal != 0) || (start != 0)) {
        if ((start & 1) != (goal & 1)) {
            count++;
        }
        start >>= 1;
        goal >>= 1;
    }
    return count;
    
}

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

尚未有邦友留言

立即登入留言