Clean, efficient algorithm for wrapping integers in C++

后端 未结 14 2062
慢半拍i
慢半拍i 2020-12-13 09:21
/**
  * 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 con         


        
14条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 10:08

    My other post got nasty, all that 'corrective' multiplication and division got out of hand. After looking at Martin Stettner's post, and at my own starting conditions of (N-L)%H+L, I came up with this:

    int Wrap(N,L,H){
      H=H-L+1; N=(N-L)%H+L; if(N

    At the extreme negative end of the integer range it breaks as my other one would, but it will be faster, and is a lot easier to read, and avoids the other nastiness that crept in to it.

    Crow.

提交回复
热议问题