📜  使用按位与运算符N除以4时找到余数

📅  最后修改于: 2021-05-25 01:50:06             🧑  作者: Mango

给定数字N ,任务是使用按位与运算符N除以4时找到余数。
例子:

Input: N = 98 
Output: 2
Explanation: 
98 % 4 = 2. Hence the output is 2.
 
Input: 200
Output: 0
Explanation: 
200 % 4 = 0. Hence output is 0.

天真的方法:
为了解决上述问题,我们可以使用天真的方法,通过使用Modulo(%)运算符来找到余数。但是,模运算符在计算上是昂贵的,并且该方法是无效的。
高效方法:
如果我们仔细观察N的二进制表示形式及其4的余数,我们将观察到余数只是N中最右边的两位。要获得数字N中最右边的两位,我们用3进行按位AND(&),因为3表示二进制是0011。为了更好地理解该方法,让我们看一下下面的图片:

下面是上述方法的实现:

C
// C implementation to find N
// modulo 4 using Bitwise AND operator
 
#include 
 
// Function to find the remainder
int findRemainder(int n)
{
 
    // Bitwise AND with 3
    int x = n & 3;
 
    // return  x
    return x;
}
 
// Driver code
int main()
{
 
    int N = 43;
    int ans = findRemainder(N);
 
    printf("%d", ans);
 
    return 0;
}


C++
// C++ implementation to find N
// modulo 4 using Bitwise AND operator
 
#include 
using namespace std;
 
// Function to find the remainder
int findRemainder(int n)
{
    // Bitwise AND with 3
    int x = n & 3;
 
    // Return  x
    return x;
}
 
// Driver code
int main()
{
 
    int N = 43;
 
    int ans = findRemainder(N);
 
    cout << ans << endl;
 
    return 0;
}


Java
// Java implementation to find N
// modulo 4 using Bitwise AND operator
 
class Main {
 
    // Driver code
    public static void main(String[] args)
    {
 
        int N = 43;
 
        int ans = findRemainder(N);
 
        System.out.println(ans);
    }
 
    // Function to find the remainder
    public static int findRemainder(int n)
    {
        // Bitwise AND with 3
        int x = n & 3;
 
        // return  x
        return x;
    }
}


Python 3
# Python 3 implementation to find N
# modulo 4 using Bitwise AND operator
 
# Function to find the remainder
def findRemainder(n):
    # Bitwise AND with 3
    x = n & 3
 
    # Return  x
    return x
 
# Driver code
if __name__ == '__main__':
    N = 43
 
    ans = findRemainder(N)
 
    print(ans)
     
# This code is contributed by Surendra_Gangwar


C#
// C# implementation to find N
// modulo 4 using Bitwise AND operator
using System;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        int N = 43;
  
        int ans = findRemainder(N);
  
        Console.Write(ans);
    }
  
    // Function to find the remainder
    public static int findRemainder(int n)
    {
        // Bitwise AND with 3
        int x = n & 3;
  
        // return  x
        return x;
    }
}
 
# This code is contributed by chitranayal


Javascript


输出:
3

时间复杂度: O(1)