<p>我假设,通过进位的次数,你想知道一次进位发生了多少次,而不是进位总数。例如,34×48的第一步有一个乘法进位(当4和8相乘时携带3),即使总进位值等于3。在</p>
<p>另外,我假设你还想知道做乘法运算时发生的加法进位数。继续我们的例子,当我们乘以34*40时,我们有一个乘法进位(4*4)。我们现在需要添加两个结果(272和1360)。这将导致一个额外的进位,进位操作的总数等于3。在</p>
<p>基本上,我计算总进位数,不包括超过最大数的进位。这意味着90*9没有任何进位。同样,90+99也不会有任何进位。我是根据你的加法运算方式决定的。如果您不希望发生这种情况,并且希望包含最后一位的进位,只需按照<code>**** ... ****</code>注释中所述的代码更改进行操作。在</p>
<p>代码如下。我包含了我自己的计算加法进位的实现。它应该在功能上等同于您发布的代码。在</p>
<pre><code>def num_add_carries(x, y):
"""
Return a count of the number of addition carries.
@param x: A number to add, as an integer.
@param y: A number to add, as an integer.
@return: The total number of carry operations.
"""
# Determine which number is the larger one
if y <= x:
min_num = y; max_num = x
else:
min_num = x; max_num = y
# Initialize some parameters
num_carries = 0
smin = str(min_num); smin_length = len(smin)
smax = str(max_num); smax_length = len(smax)
# Determine the end looping parameter
# **** Set to '-1' to include the end carry ****
end_ix = -1 if smin_length != smax_length else 0
# Iteratively perform the multiplication, counting the mult carries
for i, ix in enumerate(xrange(smin_length - 1, end_ix, -1), 1):
if int(smax[-i]) + int(smin[ix]) > 9:
num_carries += 1
return num_carries
def num_mult_carries(x, y):
"""
Return a count of the total number of multiplication carries, including
all necessary addition carries.
@param x: A number to add, as an integer.
@param y: A number to add, as an integer.
@return: The total number of carry operations.
"""
# Determine which number is the larger one
if y <= x:
min_num = y ; max_num = x
else:
min_num = x; max_num = y
# Initialize some parameters
num_carries = 0; adds = [] # List of numbers to add
smin = str(min_num); smin_length = len(smin)
smax = str(max_num); smax_length = len(smax)
# Iteratively perform the multiplication, counting the mult carries
for i, ix in enumerate(xrange(smin_length - 1, -1, -1)):
# Perform Multiplication (used for summing, later)
adds.append(max_num * int(smin[ix]) * (10 ** i))
# Determine number of multiplication carries
# **** Change the '0' to '-1' to include the end carry ****
for ix2 in xrange(smax_length - 1, 0, -1):
if int(smax[ix2]) * int(smin[ix]) > 9:
num_carries += 1
# Iteratively perform the addition, counting the addition carries
s = 0
while len(adds) > 1:
s += adds.pop(0)
num_carries += num_add_carries(s, adds[0])
return num_carries
print num_add_carries(99, 99)
print num_mult_carries(657, 34)
</code></pre>
<p>上述代码的输出为:</p>
^{pr2}$