Negative number modulo in swift

前端 未结 4 794
攒了一身酷
攒了一身酷 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:07

    An answer inspired by cdeerinck, which sacrifices speed for simplicity, is this:

    infix operator %%
    
    extension Int {
    
        static  func %% (_ left: Int, _ right: Int) -> Int {
           let mod = left % right
           return mod >= 0 ? mod : mod + right
        }
    
    }
    

    I tested it with this little loop in a playground:

    for test in [6, 5, 4, 0, -1, -2, -100, -101] {
        print(test, "%% 5", test %% 5)
    }
    

提交回复
热议问题