Recognizing when to use the modulus operator

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

    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;
    }
    

提交回复
热议问题