清洁,高效的算法在C包装整数++高效、整数、算法、清洁

2023-09-11 02:02:41 作者:凉风慕槿篱

  / **
  *返回一个数字kLowerBound和kUpperBound之间
  *例如为:环绕(-1,0,4); //返回4
  *例如为:环绕(5,0,4); //返回0
  * /
INT包裹(INT常量的kX,INT常量kLowerBound,INT常量kUpperBound)
{
    //推荐的实现?
}
 

解决方案

A%B的标志只被定义,如果 A B 都是非负的。

  INT包裹(INT的kX,INT常量kLowerBound,INT常量kUpperBound)
{
    INT range_size = kUpperBound  -  kLowerBound + 1;

    如果(KX< kLowerBound)
        的kX + = range_size *((kLowerBound  -  KX)/ range_size + 1);

    返回kLowerBound +(KX  -  kLowerBound)%range_size;
}
 

/**
  * 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?
}
算法心得 高效算法的奥密 第二版

解决方案

The sign of a % b is only defined if a and b are both non-negative.

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;
}

 
精彩推荐
图片推荐