Recognizing when to use the modulus operator

前端 未结 19 1015
醉梦人生
醉梦人生 2020-11-29 16:40

I know the modulus (%) operator calculates the remainder of a division. How can I identify a situation where I would need to use the modulus operator?

I know I can u

19条回答
  •  孤街浪徒
    2020-11-29 17:02

    Converting linear data structure to matrix structure: where a is index of linear data, and b is number of items per row:

    row = a/b
    column = a mod b
    

    Note above is simplified logic: a must be offset -1 before dividing & the result must be normalized +1.

    Example: (3 rows of 4)

    1  2  3  4    
    5  6  7  8    
    9 10 11 12 
    
    (7 - 1)/4 + 1 = 2
    
    7 is in row 2
    
    (7 - 1) mod 4 + 1 = 3 
    
    7 is in column 3
    

    Another common use of modulus: hashing a number by place. Suppose you wanted to store year & month in a six digit number 195810. month = 195810 mod 100 all digits 3rd from right are divisible by 100 so the remainder is the 2 rightmost digits in this case the month is 10. To extract the year 195810 / 100 yields 1958.

提交回复
热议问题