過了一半,該開始挑戰一天寫3題了~
tags: Easy、Bitwise
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
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;
}
bool hasAlternatingBits(int n) {
while (n != 0) {
if ((n & 1) == ((n>>1) & 1)) {
return false;
}
n >>= 1;
}
return true;
}
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;
}
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;
}