Toggle all odd bits of a number
Given n number, the task is to toggle odd bit of the number.
Examples:
Input : 10
Output : 15
binary representation 1 0 1 0
after toggle 1 1 1 1
Input : 20
Output : 1
binary representation 1 0 1 0 0
after toggle 0 0 0 0 1
1. First generate a number that contains odd position bits.
2. Take XOR with the original number. Note that 1 ^ 1 = 0 and 1 ^ 0 = 1.
Let’s understand this approach with below code.
C++
#include <iostream>
using namespace std;
int evenbittogglenumber( int n)
{
int res = 0, count = 0;
for ( int temp = n; temp > 0; temp >>= 1) {
if (count % 2 == 0)
res |= (1 << count);
count++;
}
return n ^ res;
}
int main()
{
int n = 11;
cout << evenbittogglenumber(n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int evenbittogglenumber( int n)
{
int res = 0 , count = 0 ;
for ( int temp = n; temp > 0 ; temp >>= 1 ) {
if (count % 2 == 0 )
res |= ( 1 << count);
count++;
}
return n ^ res;
}
public static void main(String args[])
{
int n = 11 ;
System.out.println(evenbittogglenumber(n));
}
}
|
Python3
def evenbittogglenumber(n) :
res = 0 ; count = 0 ; temp = n
while (temp > 0 ) :
if (count % 2 = = 0 ) :
res = res | ( 1 << count)
count = count + 1
temp >> = 1
return n ^ res
if __name__ = = '__main__' :
n = 11
print (evenbittogglenumber(n))
|
C#
using System;
class GFG {
static int evenbittogglenumber( int n)
{
int res = 0, count = 0;
for ( int temp = n; temp > 0; temp >>= 1)
{
if (count % 2 == 0)
res |= (1 << count);
count++;
}
return n ^ res;
}
public static void Main()
{
int n = 11;
Console.WriteLine(evenbittogglenumber(n));
}
}
|
PHP
<?php
function evenbittogglenumber( $n )
{
$res = 0;
$count = 0;
for ( $temp = $n ; $temp > 0; $temp >>= 1)
{
if ( $count % 2 == 0)
$res |= (1 << $count );
$count ++;
}
return $n ^ $res ;
}
$n = 11;
echo evenbittogglenumber( $n );
?>
|
Javascript
<script>
function evenbittogglenumber(n)
{
let res = 0, count = 0;
for (let temp = n; temp > 0; temp >>= 1) {
if (count % 2 == 0)
res |= (1 << count);
count++;
}
return n ^ res;
}
let n = 11;
document.write(evenbittogglenumber(n));
</script>
|
Output :
14
Time Complexity : O(log n)
Space Complexity : O(1)
Last Updated :
27 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...