/** * 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仅当a和b均为非负时,才定义符号。
a % b
a
b
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; }