📜  使用按位运算符将任何数字乘以4

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

我们是数字n,我们的任务是使用按位运算符将数字乘以4。
例子:

Input : 4
Output :16

Input :5
Output :20

解释情况1:-n = 4,二进制数4是100,现在右移两位,然后10000,现在数字是16,即乘以4 * 4 = 16 ans。
方法:-( n << 2)右移两位

C++
// C++ program to multiply a number with
// 4 using Bitwise Operator
#include 
using namespace std;
 
// function the return multiply a number
//  with 4 using bitwise operator
int multiplyWith4(int n)
{
    // returning a number with multiply
    // with 4 using2 bit shifring right
    return (n << 2);
}
 
// derive function
int main()
{
    int n = 4;
    cout << multiplyWith4(n) << endl;
    return 0;
}


Java
// Java program to multiply a number
// with 4 using Bitwise Operator
 
class GFG {
     
// function the return
// multiply a number
// with 4 using bitwise
// operator
static int multiplyWith4(int n)
{
     
    // returning a number
    // with multiply with
    // 4 using 2 bit shifting
    // right
    return (n << 2);
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 4;
    System.out.print(multiplyWith4(n));
}
}
 
// This code is contributed by Smitha.


Python 3
# Python 3 program to multiply
# a number with 4 using Bitwise
# Operator
 
# function the return multiply
# a number with 4 using bitwise
# operator
def multiplyWith4(n):
 
    # returning a number with
    # multiply with 4 using2
    # bit shifring right
    return (n << 2)
 
# derive function
n = 4
print(multiplyWith4(n))
 
# This code is contributed
# by Smitha


C#
// C# program to multiply a number
// with 4 using Bitwise Operator
using System;
 
class GFG {
     
// function the return
// multiply a number
// with 4 using bitwise
// operator
static int multiplyWith4(int n)
{
     
    // returning a number
    // with multiply with
    // 4 using 2 bit shifting
    // right
    return (n << 2);
}
 
// Driver Code
public static void Main(String[] args)
{
    int n = 4;
    Console.Write(multiplyWith4(n));
}
}
 
// This code is contributed by Smitha.


PHP


Javascript


输出 :-

16

概括:通常,我们可以使用按位运算运算符乘以2的幂。例如,假设我们希望乘以16(即2 4 ),则可以通过左移4来实现。