Day 76 位運(yùn)算: 1356. 根據(jù)數(shù)字二進(jìn)制下 1 的數(shù)目排序

('a' | ' ') = 'a'
('A' | ' ') = 'a'
('b' & '_') = 'B'
('B' & '_') = 'B'
('d' ^ ' ') = 'D'
('D' ^ ' ') = 'd'
不用臨時(shí)變量交換兩個(gè)數(shù)
int a = 1, b = 2;
a ^= b;
b ^= a;
a ^= b;
// 現(xiàn)在 a = 2, b = 1
加一
int n = 1;
n = -~n;
// 現(xiàn)在 n = 2
減一
int n = 2;
n = ~-n;
// 現(xiàn)在 n = 1
判斷兩個(gè)數(shù)是否異號(hào)
int x = -1, y = 2;
boolean f = ((x ^ y) < 0); // true
int x = 3, y = 2;
boolean f = ((x ^ y) < 0); // false
利用的是補(bǔ)碼編碼的符號(hào)位。整數(shù)編碼最高位是符號(hào)位,負(fù)數(shù)的符號(hào)位是 1,非負(fù)數(shù)的符號(hào)位是 0,再借助異或的特性,可以判斷出兩個(gè)數(shù)字是否異號(hào)。

n & (n-1) 的運(yùn)用
n & (n-1) 這個(gè)操作在算法中比較常見(jiàn),作用是消除數(shù)字 n 的二進(jìn)制表示中的最后一個(gè) 1。

191. Number of 1 Bits

class Solution:
    def hammingWeight(self, n: int) -> int:
        res = 0
        while n != 0:
            n = n & (n-1)
            res += 1
        return res 

231. Power of Two

一個(gè)數(shù)如果是 2 的指數(shù),那么它的二進(jìn)制表示一定只含有一個(gè) 1.

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n <= 0:
            return False 
        return (n & (n-1)) == 0

a ^ a = 0 的運(yùn)用

一個(gè)數(shù)和它本身做異或運(yùn)算結(jié)果為 0,即 a ^ a = 0;一個(gè)數(shù)和 0 做異或運(yùn)算的結(jié)果為它本身,即 a ^ 0 = a。

136. Single Number

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        res = 0
        for i in range(len(nums)):
            res = res ^ nums[i] 
        return res 

268. Missing Number

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        n = len(nums) 
        res = n
        for i in range(n):
            res = res ^ (i ^ nums[i])
        return res  

1356. 根據(jù)數(shù)字二進(jìn)制下 1 的數(shù)目排序

  • 思路
    • example
    • 計(jì)算每個(gè)數(shù)字的二進(jìn)制含1的個(gè)數(shù),然后按此排序 (先含1個(gè)數(shù)大小,后數(shù)值本身大?。?/li>
  • 復(fù)雜度. 時(shí)間:O(), 空間: O()
class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        def countOne(num):
            res = 0
            while num:
                if num % 2 == 1:
                    res += 1
                num = num // 2 
            return res  
        arr.sort(key=lambda num: (countOne(num), num))  
        return arr 
  • 位運(yùn)算

n = n & (n-1) # 清除最低位的1


class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        def countOnes(num):
            res = 0
            while num != 0:
                num = num & (num-1)
                res += 1
            return res  
        arr.sort(key=lambda x: (countOnes(x), x))
        return arr 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容