给定数字n 。问题是不使用算术运算运算符就可以有效地检查n是否为4的倍数。
例子:
Input : 16
Output : Yes
Input : 14
Output : No
方法: 4的倍数在二进制表示中始终以00作为其后两位。我们必须检查n的最后两位是否未设置。
如何检查最后两位是否未设置。
如果n&3 == 0,则后两位未设置,否则将两者或其中之一置位。
C/C++
// C++ implementation to efficiently check whether n
// is a multiple of 4 or not
#include
using namespace std;
// function to check whether 'n' is
// a multiple of 4 or not
string isAMultipleOf4(int n)
{
// if true, then 'n' is a multiple of 4
if ((n & 3) == 0)
return "Yes";
// else 'n' is not a multiple of 4
return "No";
}
// Driver program to test above
int main()
{
int n = 16;
cout << isAMultipleOf4(n);
return 0;
}
Java
// Java implementation to efficiently check
// whether n is a multiple of 4 or not
class GFG {
// method to check whether 'n' is
// a multiple of 4 or not
static boolean isAMultipleOf4(int n)
{
// if true, then 'n' is a multiple of 4
if ((n & 3) == 0)
return true;
// else 'n' is not a multiple of 4
return false;
}
// Driver method
public static void main(String[] args)
{
int n = 16;
System.out.println(isAMultipleOf4(n) ? "Yes" : "No");
}
}
Python 3
# Python 3 implementation to
# efficiently check whether n
# is a multiple of 4 or not
# function to check whether 'n'
# is a multiple of 4 or not
def isAMultipleOf4(n):
# if true, then 'n' is
# a multiple of 4
if ((n & 3) == 0):
return "Yes"
# else 'n' is not a
# multiple of 4
return "No"
# Driver Code
if __name__ == "__main__":
n = 16
print (isAMultipleOf4(n))
# This code is contributed
# by ChitraNayal
C#
// C# implementation to efficiently check
// whether n is a multiple of 4 or not
using System;
class GFG {
// method to check whether 'n' is
// a multiple of 4 or not
static bool isAMultipleOf4(int n)
{
// if true, then 'n' is a multiple of 4
if ((n & 3) == 0)
return true;
// else 'n' is not a multiple of 4
return false;
}
// Driver method
public static void Main()
{
int n = 16;
Console.WriteLine(isAMultipleOf4(n) ? "Yes" : "No");
}
}
// This code is contributed by vt_m.
PHP
输出:
Yes
我们可以概括以上解决方案吗?
同样,我们可以检查2的其他幂。例如,如果n&7为0,则数字n将是8的倍数。通常可以说。
// x must be a power of 2 for below
// logic to work
if (n & (x -1) == 0)
n is a multiple of x
Else
n is NOT a multiple of x