Multiply any Number with 4 using Bitwise Operator
Last Updated :
25 Nov, 2022
We are a Number n and our task is to multiply the number by 4 using a bit-wise Operator.
Examples:
Input : 4
Output :16
Input :5
Output :20
Explanation Case 1:- n=4 the binary of 4 is 100 and now shifts two bit right then 10000 now the number is 16 is multiplied 4*4=16 ans.
Approach :- (n<<2) shift two bit right
C++
#include <bits/stdc++.h>
using namespace std;
int multiplyWith4( int n)
{
return (n << 2);
}
int main()
{
int n = 4;
cout << multiplyWith4(n) << endl;
return 0;
}
|
Java
class GFG {
static int multiplyWith4( int n)
{
return (n << 2 );
}
public static void main(String[] args)
{
int n = 4 ;
System.out.print(multiplyWith4(n));
}
}
|
Python 3
def multiplyWith4(n):
return (n << 2 )
n = 4
print (multiplyWith4(n))
|
C#
using System;
class GFG {
static int multiplyWith4( int n)
{
return (n << 2);
}
public static void Main(String[] args)
{
int n = 4;
Console.Write(multiplyWith4(n));
}
}
|
PHP
<?php
function multiplyWith4( $n )
{
return ( $n << 2);
}
$n = 4;
echo multiplyWith4( $n ), "\n" ;
?>
|
Javascript
<script>
function multiplyWith4(n)
{
return (n << 2);
}
var n = 4;
document.write(multiplyWith4(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Generalization : In general, we can multiply with a power of 2 using bitwise operators. For example, suppose we wish to multiply with 16 (which is 24), we can do it by left shifting by 4.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...