c++ - 用于在 C++ 中包装整数的干净、高效的算法

标签 c++ algorithm math word-wrap integer

/**
  * Returns a number between kLowerBound and kUpperBound
  * e.g.: Wrap(-1, 0, 4); // Returns 4
  * e.g.: Wrap(5, 0, 4); // Returns 0      
  */
int Wrap(int const kX, int const kLowerBound, int const kUpperBound)
{
    // Suggest an implementation?
}

最佳答案

a % b 的符号只有在 ab 都是非负数时才被定义。

int Wrap(int kX, int const kLowerBound, int const kUpperBound)
{
    int range_size = kUpperBound - kLowerBound + 1;

    if (kX < kLowerBound)
        kX += range_size * ((kLowerBound - kX) / range_size + 1);

    return kLowerBound + (kX - kLowerBound) % range_size;
}

关于c++ - 用于在 C++ 中包装整数的干净、高效的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/707370/

相关文章:

c# - BSTR (COM) 的长度

c++ - 控制台上的不同输出打印标准输出/重定向到文件

arrays - 找出比较两个项目的概率。 (请提示)

algorithm - 数据结构面试

javascript - 根据其他属性从对象数组中提取属性

c++ - C++ “undefined reference to…”

c++ - 改变边界时平移轴

php - 这是显示没有小数点的货币数值的好方法吗?

language-agnostic - 函数近似

math - 将极角映射到 0..1