contributed by < shauming1020
>
homework
unsigned
的系統上,[] 內總是為 0return
回推,透過 (fix ^ (fix >> n))
造出 mask ,並讓 (m >> n)
所產生的 [] 可以根據不同系統而對應到正確的值const int logical = (((int) -1) OP1) > 0;
unsigned int fixu = -(logical & (OP2));
fix >> 2
結果為 0x[00]11,再與 fix 做 運算得 0x[11]00,為我們預期的 maskBuilt-in Function: int __builtin_ctz (unsigned int x)
Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.
(num & (num - 1))==0
!(__builtin_ctz(num) OPQ)
Leetcode 1342. Number of Steps to Reduce a Number to Zero
Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
Built-in Function: int __builtin_clz (unsigned int x)
- Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.
population count 簡稱 popcount 或叫 sideways sum,是計算數值的二進位表示中,有多少位元是 1
For a given number N in base-10, return the complement of it's binary representation as a base-10 integer.
Example 1:
Input: 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
runtime error: passing zero to clz(), which is not a valid argument (solution.c)
的警示,因此需要額外考慮 N = 0 的情況Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
參考Binary GCD Algorithm 和 Greatest Common Divisor 特性和實作考量
- If x and y are both even, gcd(x, y) = 2*gcd(x/2, y/2) because 2 is a common divisor.
Multiplication with 2 can be done with bitwise shift operator.
- If x is even and y is odd, gcd(x, y) = gcd(x/2, y).
- On similar lines, if x is odd and y is even, then
gcd(x, y) = gcd(x, y/2). It is because 2 is not a common divisor.- If both x and y are odd, then gcd(x, y) = gcd(|x-y|/2, y)
Repeat steps until x = y, or until x = 0.
return YYY;
the GCD is power(2, k) * y, where power(2, k) is 2 raise to the power of k and k is the number of common factors of 2 found in step 2.
可用 ctz 改寫為效率更高且等價的程式碼:
for (int i = 0; i < 64; i++) {
搜尋整個 bitsetif ((bitset >> i) & 0x1)
不斷將 bitset 右移判斷,如果 bitset 的 LSB 為 1out[pos++] = p + i;
則將該位置 p + i 放到 out 中uint64_t bitset;
一次存放一組 bit array,當 bitset 不為 0,表示當中存在 bit 1int r = __builtin_ctzll(bitset);
會計算 bitset 尾端有幾個 0,此時 r = 1,即可知道位於 k * 64 + 1 的位置有 bit 1,而矩陣 index 從 0 起算,因此尾端有幾個 0 恰可直接當作 indexbitset ^= t;
將 bitset 與 mask t 進行 運算,而先前已經計算過 [] 中的 1 ( ),因此希望造出的 mask 可讓 [] 設成 0,並保留其他地方,如此一來 ,即可用 ctz 計算出下一個 1 的位置