Geeksforgeeks

Error

×

Leaderboard

Showing:

Handle | Score |
---|---|

@Ibrahim Nash | 6560 |

@blackshadows | 6400 |

@mb1973 | 5777 |

@Quandray | 5275 |

@akhayrutdinov | 5111 |

@saiujwal13083 | 5074 |

@kirtidee18 | 4398 |

@sanjay05 | 3762 |

@mantu_singh | 3654 |

@gfgaccount | 3601 |

@marius_valentin_dragoi | 3525 |

Complete Leaderboard | |

Handle | Score |

@anish5256 | 991 |

@vimleshpratapsingh321 | 980 |

@skj7 | 899 |

@akhileshkumar562002 | 862 |

@kanewilliamson123 | 854 |

@pradeeppatidar1999 | 852 |

@pd420786 | 813 |

@infilooop | 800 |

@bunnybug320 | 796 |

@smitabose7826 | 784 |

@wallflowe101 | 778 |

Complete Leaderboard |

Given an unsigned integer **N**. The task is to swap all odd bits with even bits. For example, if the given number is 23 (**0**0**0**1**0**1**1**1), it should be converted to 43(0**0**1**0**1**0**1**1**). Here, every even position bit is swapped with adjacent bit on the right side(even position bits are highlighted in the binary representation of 23), and every odd position bit is swapped with an adjacent on the left side.

**Example 1**:

**Input**: N = 23
**Output**: 43
**Explanation**:
Binary representation of the given number
is **0**0**0**1**0**1**1**1 after swapping
0**0**1**0**1**0**11 = 43 in decimal.

**Example 2**:

**Input**: N = 2
**Output**: 1
**Explanation**:
Binary representation of the given number
is **1**0 after swapping 0**1 **= 1 in decimal.

**Your Task: **Your task is to complete the function **swapBits**() which takes an integer and **returns an **integer with all the odd and even bits swapped.

**Expected Time Complexity:** O(1).

**Expected Auxiliary Space:** O(1).

**Constraints:**

1 ≤ N ≤ 10^{9}

Login to report an issue on this page.

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

YesLoading...

Swap all odd and even bits

...