Recognizing when to use the modulus operator

前端 未结 19 911
醉梦人生
醉梦人生 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:13

    Best use of modulus operator I have seen so for is to check if the Array we have is a rotated version of original array.

    A = [1,2,3,4,5,6] B = [5,6,1,2,3,4]

    Now how to check if B is rotated version of A ?

    Step 1: If A's length is not same as B's length then for sure its not a rotated version.

    Step 2: Check the index of first element of A in B. Here first element of A is 1. And its index in B is 2(assuming your programming language has zero based index). lets store that index in variable "Key"

    Step 3: Now how to check that if B is rotated version of A how ??

    This is where modulus function rocks :

    for (int i = 0; i< A.length; i++)
    {
    
    // here modulus function would check the proper order. Key here is 2 which we recieved from Step 2
       int j = [Key+i]%A.length;
    
       if (A[i] != B[j])
       {
         return false;
       }
    }
    
    return true;
    

提交回复
热议问题