Recognizing when to use the modulus operator

前端 未结 19 804
醉梦人生
醉梦人生 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 16:48

    The modulo can be useful to convert and split total minutes to "hours and minutes":

    hours = minutes / 60

    minutes_left = minutes % 60

    In the hours bit we need to strip the decimal portion and that will depend on the language you are using.

    We can then rearrange the output accordingly.

    0 讨论(0)
  • 2020-11-29 16:48

    One use case I saw recently was when you need to reverse a number. So that 123456 becomes 654321 for example.

    int number   = 123456;
    int reversed = 0;
    
    while ( number > 0 ) {
        # The modulus here retrieves the last digit in the specified number
        # In the first iteration of this loop it's going to be 6, then 5, ...
        # We are multiplying reversed by 10 first, to move the number one decimal place to the left.
        # For example, if we are at the second iteration of this loop, 
        #  reversed gonna be 6, so 6 * 10 + 12345 % 10 => 60 + 5
        reversed = reversed * 10 + number % 10;
        number = number / 10;
    }
    
    0 讨论(0)
  • 2020-11-29 16:48

    It's an easy way to tell if a number is even or odd. Just do # mod 2, if it is 0 it is even, 1 it is odd.

    0 讨论(0)
  • 2020-11-29 16:49
    • Wrapping values (like a clock).
    • Provide finite fields to symmetric key algorithms.
    • Bitwise operations.

    And so on.

    0 讨论(0)
  • 2020-11-29 16:52

    My favorite use is for iteration.

    Say you have a counter you are incrementing and want to then grab from a known list a corresponding items, but you only have n items to choose from and you want to repeat a cycle.

    var indexFromB = (counter-1)%n+1;

    Results (counter=indexFromB) given n=3:

    `1=1`
    `2=2`
    `3=3`
    `4=1`
    `5=2`
    `6=3`
    ...
    
    0 讨论(0)
  • 2020-11-29 16:53

    Often, in a loop, you want to do something every k'th iteration, where k is 0 < k < n, assuming 0 is the start index and n is the length of the loop.

    So, you'd do something like:

    int k = 5;
    int n = 50;
    for(int i = 0;i < n;++i)
    {
        if(i % k == 0)  // true at 0, 5, 10, 15..
        {
            // do something
        }
    }
    

    Or, you want to keep something whitin a certain bound. Remember, when you take an arbitrary number mod something, it must produce a value between 0 and that number - 1.

    0 讨论(0)
提交回复
热议问题