Web Toolbar by Wibiya

Pages

Wednesday, October 26, 2011

Given an integer n, write code to calculate n+1, without using +,-,++,--,*,/

Solution# 1: Start from the LSB and keep setting them to 0 till we find the first 0. And then set that 0 to 1. Here is the code,

#include 
#include 

int increment(int n)
{
    int i = 1;

    while(i&n)
    {
        n = n & ~i;
        i = i<<1;
    }

    return n|i;
}

int main()
{
    printf("%d\n", increment(5));
    return 0;
}

No comments: