python 内部自带大整数运算能力,整数运算不会溢出,只要内存足够,就oK
下面的例子演示了两个32位整数加法的情况(通过位运算实现),为了模拟溢出的效果,必须人工的进行位运算,~运算符除了求反,还是二进制的补运算符,运算过后的二进制数字按照补码解释,例如 ~(0011 1100) = (1100 0011) = -61
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
def getSum(a, b): """ :type a: int :type b: int :rtype: int """ MAX = 0X7fffffff MIN = 0X80000000 while b ! = 0 : a,b = a^b,(a&b)<< 1 print ( " a = {0:b},b = {1:b}" . format (a,b)) return a def getSum_(a, b): """ :type a: int :type b: int :rtype: int """ MAX = 0x7FFFFFFF MIN = 0x80000000 mask = 0xFFFFFFFF while b ! = 0 : a, b = (a ^ b) & mask, ((a & b) << 1 ) & mask print ( type (a)) print ( " a = {0:b},b = {1:b}" . format (a,b)) return a if a < = MAX else ~(a^mask) print (getSum_( - 1 , - 1 )) print (getSum( - 1 , 1 )) |
补充:python 循环内部添加多个条件判断会出现越界
1.循环遍历数组是,想添加条件修改时,只删除第一个
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# -*- coding: utf-8 -*- a = [ 11 , 22 , 33 , 44 , 55 ] for i in a: if i = = 11 or i = = 22 : a.remove(i) for i in a: print (i) ''' 33 55 [Finished in 0.1s] ''' |
2.应该引入被删除为一个数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# -*- coding: utf-8 -*- a = [ 11 , 22 , 33 , 44 , 55 ] b = [] for i in a: if i = = 11 or i = = 22 : b.append(i) for i in b: a.remove(i) for i in a: print (i) ''' 33 44 55 [Finished in 0.1s] ''' |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/man_sion/article/details/72510284