Bitwise Operators: Add 1 to a given number

Problem Statement:

You need to add 1 to given number using bitwise operations.

Example:

Input: 10
Output: 11

Solution 1

To add 1 to any number, flip all bits till the rightmost 0 bit.

Then flip rightmost 0 bit.

If the number is 0011000111, flip all bits till rightmost 0 bit 0011000000, then flip rightmost 0 bit, 0011001000

Code Solution


#include<iostream>
using namespace std;

 
int solution(int x) 
{ 
    int m = 1; 
     
    // filp all bits till rightmost 0
    while( x & m ) 
    { 
        x = x ^ m; 
        m <<= 1; 
    } 
     
    // flip the rightmost 0 bit 
    x = x ^ m; 
    return x; 
} 
 
int main() 
{ 
    cout<<solution(10); 
    return 0; 
} 
 

Output

11

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *