余数计算填充的简单方法

余数计算填充的简单方法

本文介绍了基于模数/余数计算填充的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个长度为L = 77的字符串,我希望将其填充为N = 10的倍数的长度.我对仅计算所需的填充量感兴趣.使用N - (L % N)可以很容易地做到这一点,除了L % N为零的情况.

If I have a string of length L=77 that I want to pad to a length that is a multiple of N=10. I am interested in computing just the amount of padding required. This can be easily done with N - (L % N), except for cases where L % N is zero.

我现在一直在使用以下内容:

I have been using the following for now:

pad = (N - (L % N)) % N

这似乎不是特别清晰,所以有时我会用

This does not seem particularly legible, so sometimes I use

pad = N - (L % N)
if pad == N:
    pad = 0

对于这么简单的事情,使用三行代码似乎是矫kill过正.

It seems overkill to use three lines of code for something so simple.

或者,我可以找到k * N >= Lk,但是使用math.ceil似乎也过分了.

Alternatively, I can find the k for which k * N >= L, but using math.ceil seems like overkill as well.

我还有更好的选择吗?也许某个地方有一个简单的功能?

Is there a better alternative that I am missing? Perhaps a simple function somewhere?

推荐答案

负L的模量可以做到这一点.

The modulus of negative L will do it.

pad = -L % N

这篇关于基于模数/余数计算填充的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:41