Skip to content

Commit d6d0c41

Browse files
committed
python 负数位运算的坑
1 parent 5c76544 commit d6d0c41

File tree

1 file changed

+20
-3
lines changed
  • docs/19_python内置常用算法和数据结构

1 file changed

+20
-3
lines changed

docs/19_python内置常用算法和数据结构/builtins.md

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ sys.setrecursionlimit(100000) # 设置函数栈深度足够大,避免栈溢出
6464
# python int 值范围
6565

6666
```
67-
# 乘方 (比较推荐,py2/3 都兼容不容易出错)
67+
# 乘方 (比较推荐⭐️,py2/3 都兼容不容易出错)
6868
MAXINT = 2**63-1
6969
MININT = -2**63
7070
@@ -81,6 +81,23 @@ MAXINT = (1<<63) - 1
8181
MININT = ~MAXINT
8282
```
8383

84+
# python 负数位运算的坑
85+
1. Python3 中的整型是补码形式存储的
86+
2. Python3 中 bin 一个负数(十进制表示),输出的是它的原码的二进制表示加上个负号
87+
3. 为了获得负数(十进制表示)的补码,需要手动将其和十六进制数 0xffffffff 进行按位与操作,得到结果是个十六进制数,再交给 bin() 进行输出,
88+
得到的才是你想要的补码表示。
89+
90+
```py
91+
# 整数转换 https://leetcode-cn.com/problems/convert-integer-lcci/
92+
class Solution:
93+
def convertInteger(self, A: int, B: int) -> int:
94+
return bin((A & 0xffffffff) ^ (B & 0xffffffff)).count('1')
95+
```
96+
97+
参考:
98+
- https://www.runoob.com/w3cnote/python-negative-storage.html
99+
- https://leetcode-cn.com/problems/convert-integer-lcci/solution/python3-zhu-yi-qi-dui-yu-fu-shu-de-cun-chu-fang-sh/
100+
84101
# python list/dict 排序等技巧
85102

86103
```py
@@ -452,7 +469,7 @@ def gen_tree(vals):
452469
return root
453470
```
454471

455-
# python 交换列表元素的坑
472+
# python 交换列表元素的坑(交换副作用)
456473

457474
```
458475
# 41. 缺失的第一个正数 https://leetcode-cn.com/problems/first-missing-positive/
@@ -474,7 +491,7 @@ class Solution(object):
474491
while 1 <= nums[i] <= n and nums[nums[i]-1] != nums[i]:
475492
# NOTE: 注意这一句交换右边有副作用的,不能颠倒!!!
476493
# nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i] # 这么写死循环!
477-
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
494+
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] # 有副作用的放前边
478495
for i in range(n):
479496
if nums[i] != i+1:
480497
return i+1

0 commit comments

Comments
 (0)