给定一个数字n,使用位运算符检查它是否可被8整除。 例如:
null
Input : 16Output :YESInput :15Output :NO
方法: 结果=((n>>3)<<3)==n)。首先我们将3位向右移位,然后将3位向左移位,然后将数字与给定的数字进行比较,如果数字等于该数字,则该数字可被8整除。 说明: 例:n=16,给定的16的二进制数是10000,现在我们右移3位,现在我们有00010,所以我们再次向左移动3位,然后我们有10000,现在与给定的数字进行比较,第一个16==16,在二进制中是真的,所以这个数可以被8整除。
CPP
// C++ program to check whether // the number is divisible by // 8 or not using bitwise operator #include <bits/stdc++.h> 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
<?php // PHP program to check whether // the number is divisible by // 8 or not using bitwise operator // function to check number is // div by 8 or not using bitwise // operator function Div_by_8( $n ) { return ((( $n >> 3) << 3) == $n ); } // Driver program $n = 16; if (Div_by_8( $n )) echo "YES" ; else echo "NO" ; //This code is contributed by mits. ?> |
Javascript
<script> // javascript program to check whether // the number is divisible by // 8 or not using bitwise operator // function to check number is // div by 8 or not using bitwise // operator function Div_by_8(n) { return (((n >> 3) << 3) == n); } // Driver code var n = 16; if (Div_by_8(n)) document.write( "YES" ); else document.write( "NO" ); // This code is contributed by Princi Singh. </script> |
YES
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END