Negative number modulo in swift

前端 未结 4 748
攒了一身酷
攒了一身酷 2020-11-30 11:33

How does modulo of negative numbers work in swift ? When i did (-1 % 3) it is giving -1 but the remainder is 2. What is the catch in it?

4条回答
  •  离开以前
    2020-11-30 12:08

    If what you are really after is capturing a number between 0 and b, try using this:

    infix operator %%
    
    extension Int {
        static  func %% (_ left: Int, _ right: Int) -> Int {
            if left >= 0 { return left % right }
            if left >= -right { return (left+right) }
            return ((left % right)+right)%right
        }
    }
    
    print(-1 %% 3) //prints 2
    

    This will work for all value of a, unlike the the previous answer while will only work if a > -b.

    I prefer the %% operator over just overloading %, as it will be very clear that you are not doing a true mod function.

    The reason for the if statements, instead of just using the final return line, is for speed, as a mod function requires a division, and divisions are more costly that a conditional.

提交回复
热议问题