📌  相关文章
📜  使用按位运算运算符检查数字是否可被8整除

📅  最后修改于: 2021-05-07 00:58:45             🧑  作者: Mango

给定一个数字n,请使用按位运算运算符来检查它是否可以被8整除。
例子:

Input : 16
Output :YES

Input :15
Output :NO

方法:结果=((((n >> 3)<< << 3)== n)。首先,我们将3位右移,然后将3位左移,然后将该数字与给定的数字进行比较(如果该数字等于该数字,则该数字可被8整除)。
解释:
示例:n = 16给定,所以16的二进制数是10000,现在我们将3位右移,现在我们得到00010,所以我们再次将3位左移,然后我们得到10000,现在与给定数比较第一个16 == 16 in二进制,所以它是真的,所以数字可以被8整除。

CPP
// C++ program to check whether
// the number is divisible by
// 8 or not using bitwise operator
#include 
using namespace std;
 
// function to check number is
// div by 8 or not using bitwise
// operator
int Div_by_8(int n)
{
    return (((n >> 3) << 3) == n);
}
 
// Driver program
int main()
{
    int n = 16;
    if (Div_by_8(n))
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
    return 0;
}


Java
// Java program to check whether
// the number is divisible by
// 8 or not using bitwise operator
import java.io.*;
import java.util.*;
 
class GFG
{
    // function to check number is
    // div by 8 or not using bitwise
    // operator
    static boolean Div_by_8(int n)
    {
        return (((n >> 3) << 3) == n);
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int n = 16;
        if (Div_by_8(n))
            System.out.println("YES");
        else
            System.out.println("NO");
         
    }
}
 
// This code is contributed by  Gitanjali


Python3
# Python  program to check whether
# the number is divisible by
# 8 or not using bitwise operator
 
import math
 
# function to check number is
# div by 8 or not using bitwise
# operator
 
def Div_by_8(n):
 
    return (((n >> 3) << 3) == n)
 
 
#  driver code
n = 16
if (Div_by_8(n)):
    print("YES")
else:
    print("NO")
 
# This code is contributed by Gitanjali.


C#
// C# program to check whether         
// the number is divisible by         
// 8 or not using bitwise operator         
using System;         
class GFG {         
            
 // function to check number is         
 // div by 8 or not using bitwise         
 // operator         
 static bool Div_by_8(int n)         
 {         
 return (((n >> 3) << 3) == n);         
 }         
            
 // Driver code         
 public static void Main ()          
 {         
 int n = 16;         
            
 if (Div_by_8(n))         
 Console.WriteLine("YES");         
 else         
 Console.WriteLine("NO");         
            
 }         
}    
      
// This code is contributed by vt_m.


PHP
> 3) << 3) == $n);
}
 
// Driver program
$n = 16;
 
if (Div_by_8($n))
    echo "YES";
else
    echo "NO";
         
//This code is contributed by mits.
?>


Javascript


YES