Leetcode 191 - Number of 1 Bits

題目

Problem#

給你一個 32-bit 的無號整數,要你回傳有幾個 1 (又稱作 Hamming weight)。

想法#

Naive: 每個 bit 都檢查是不是 1 然後記數。
Improve: 每次找最右邊的 1-bit,可以把數字 $n$ 與 $n-1$ 做 AND 運算,因為減一的話最右邊的 1 就會被消滅,經過 and 運算就會消失,直到變成 0。
或是可以用編譯器內建的 __builtin_popcount()

Read More

Leetcode 1685 - Sum of Absolute Differences in a Sorted Array

題目

Problem#

給你一個遞減排序的整數陣列 nums ,要你回傳另一個整數陣列 result[i] 代表 nums[i]nums 裡的所有數字的差距的絕對值總和。
result[i] = sum(|nums[i]-nums[j]|) where 0 <= j < nums.length && j != i

測資限制#

  • $2 \le n \le 10^5$
  • $1 \le \text{nums}[i] \le \text{nums}[i+1] \le 10^4$

Read More