Samuel Liu

Description:

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

Example 1:

Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101

Example 2:

Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.

Example 3:

Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.

Example 4:

Input: n = 10
Output: true
Explanation: The binary representation of 10 is: 1010.

Example 5:

Input: n = 3
Output: false

Constraints:

  • 1 <= n <= 231 - 1

C code solution:

bool hasAlternatingBits(int n){
int prev = n&1;
n = n >> 1;

while(n){
if(prev == (n&1)){
return false;
}

prev = n & 1;
n = n >> 1;
}
return true;
}

--

--

Description:

Reverse bits of a given 32 bits unsigned integer.

Example 1:

Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Example 2:

Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.

Constraints:

  • The input must be a binary string of length 32

C code solution:

uint32_t reverseBits(uint32_t n) {
int hash[32] = {0};
int i = 0;
// get the status of each digits into hash
while(n){
if(n&1 == 1)
hash[i] = 1;
i++;
n = n >> 1;
}
//reform the new number inversely
uint32_t res = 0;
for(i=31; i>=0; i--){
res += pow(2, 31-i) * hash[i];
}
return res;
}

--

--

利用指標,把原本的結構變數串起來。

在第一個結構後面加一個指標、讓它指向下一個結構;在第二個結構後面,再加一個指標,讓它指向下一個結構… 依次連接。

透過這樣的方式,能讓每個能彈性擴充。

當我們想在 Tzuyu 和 Mina 之間插入一個 Sana 時,就讓 Tzuyu 指向 Sana,再讓 Sana 指向後面 Mina。

--

--