191. Number of 1 Bits
Given a positive integer n
, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).
int hammingWeight(uint32_t n) {int count = 0;while (n) {count += n & 1; // 檢查最低位是否為 1n >>= 1; // 右移一位}return count;
}int main() {uint32_t n = 11; // 二進制為 1011cout << "Number of set bits: " << hammingWeight(n) << endl; // 輸出 3return 0;
}
1356. Sort Integers by The Number of 1 Bits
You are given an integer array arr
. Sort the integers in the array in ascending order by the number of 1’s in their binary representation and in case of two or more integers have the same number of 1’s you have to sort them in ascending order.
Return the array after sorting it.
給定一個整數數組 arr
,要求按照以下規則對數組進行排序:
- 按二進制表示中 1 的個數升序排序。
- 如果兩個數的二進制表示中 1 的個數相同,則按數值大小升序排序。
最后返回排序后的數組。
Easy Understanding Version
int countOnes(int num) {int count = 0;while (num) {count += num % 2;num = num / 2;}return count;
}bool wayToSort(int i, int j) {int countA = countOnes(i);int countB = countOnes(j);if (countA == countB) {return i < j;}return cntA < cntB;
}
vector<int> sortByBits(vector<int>& arr) {sort(arr.begin(), arr.end(), wayToSort);return arr;
}
Compact Version
int countOnes(int n) {return __builtin_popcount(n); // 計算二進制中 1 的個數
}vector<int> sortByBits(vector<int>& arr) {sort(arr.begin(), arr.end(), [](int a, int b) {int countA = countOnes(a);int countB = countOnes(b);if (countA == countB) {return a < b; // 如果 1 的個數相同,按數值升序排序}return countA < countB; // 否則按 1 的個數升序排序});return arr;
}