基于模数/余数计算填充的简单方法

编程入门 行业动态 更新时间:2024-10-07 16:19:17
本文介绍了基于模数/余数计算填充的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我有一个长度为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 >= L的k,但是使用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

更多推荐

基于模数/余数计算填充的简单方法

本文发布于:2023-11-29 09:10:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645966.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:余数   模数   简单   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!