Change all even bits in a number to 0
Last Updated :
22 Jun, 2022
Given a number, change all bits at even positions to 0.
Examples:
Input : 30
Output : 10
Binary representation of 11110.
Bits at Even positions are highlighted.
After making all of them 0, we get 01010
Input : 10
Output : 10
Method 1 (Bit Traversal)
The idea is to traverse through all even bits. We accumulate all powers of 2 in a number to subtract. Finally we subtract the accumulated value from n to obtain the result.
C++
#include <bits/stdc++.h>
using namespace std;
int changeEvenBits( int n)
{
int to_subtract = 0;
int m = 0;
for ( int x = n; x; x >>= 2) {
if (x & 1)
to_subtract += (1 << m);
m += 2;
}
return n - to_subtract;
}
int main()
{
int n = 30;
cout << changeEvenBits(n) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static int changeEvenBits( int n)
{
int to_subtract = 0 ;
int m = 0 ;
for ( int x = n; x > 0 ; x >>= 2 ) {
if ((x & 1 ) > 0 )
to_subtract += ( 1 << m);
m += 2 ;
}
return n - to_subtract;
}
public static void main(String[] args)
{
int n = 30 ;
System.out.println(changeEvenBits(n));
}
}
|
Python3
C#
PHP
Javascript
<script>
function changeEvenBits(n)
{
let to_subtract = 0;
let m = 0;
for (x = n; x; x >>= 2)
{
if (x & 1)
to_subtract += (1 << m);
m += 2;
}
return n - to_subtract;
}
n = 30;
document.write( changeEvenBits(n) );
</script>
|
Time Complexity – O(log n)
Space Complexity – O(1)
Method 2: (Bit masking)
C++
#include <bits/stdc++.h>
using namespace std;
int convertEvenBitToOne( int n) { return (n & 0xaaaaaaaa); }
int main()
{
int n = 30;
cout << convertEvenBitToOne(n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int convertEvenBitToOne( int n)
{
return (n & 0xaaaaaaaa );
}
public static void main(String[] args)
{
int n = 30 ;
System.out.println(convertEvenBitToOne(n));
}
}
|
Python3
def convertEvenBitToOne(n):
return (n & 0xaaaaaaaa )
n = 30
print (convertEvenBitToOne(n))
|
C#
using System;
class GFG {
static long convertEvenBitToOne( int n)
{
return (n & 0xaaaaaaaa);
}
public static void Main()
{
int n = 30;
Console.WriteLine(convertEvenBitToOne(n));
}
}
|
PHP
<?php
function convertEvenBitToOne( $n )
{
return ( $n & 0xaaaaaaaa);
}
$n = 30;
echo convertEvenBitToOne( $n );
?>
|
Javascript
<script>
function convertEvenBitToOne(n)
{
return (n & 0xaaaaaaaa);
}
n = 30;
document.write(convertEvenBitToOne(n));
</script>
|
Time Complexity – O(1)
Space Complexity – O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...