Microsoft Interview Question
Software Engineer / DevelopersThe main thing to look out for is when you have a number such as 0x0011 where adding one will carry to the next bit.
MaskA does addition using & for each bit position. For each operation if there is a carry, the result will be greater than one.
Example:
0x0011 & 0x0001 = 0x0001
0x0011 & 0x0010 = 0x0010
(and so on). As long as the result is not zero then we will have a carry bit.
MaskB is used to keep track of these carry bits, every time the result of the above operation is greater than one, we shift as follows.
0x0001->0x0011->0x0111 etc.
Once we break out of the loop we xor the original value with MaskB to get the final result. Example, 0x0011 ^ 0x0111 = 0x0100, which is what we want.
The code works for negatives!! woot!
public void bitAdd(int val){
int maskB = 0xFFFFFFFF - 1;
int maskA = 0x0001;
while(maskA>=1){
if((maskA & val) == 0){
break;
} else {
maskA = maskA << 1;
maskB = maskB << 1;
}
}
System.out.println("Adding one:" + (val ^ ~(maskB)));
}
<pre lang="" line="1" title="CodeMonkey45223" class="run-this">#include<stdio.h>
#include<stdlib.h>
int main(int argc,char **argv)
{
if(argc<2) {printf("Usage ./a.out int\n"); return -1;}
int number=atoi(argv[1]);
unsigned char *charPointer = NULL;
charPointer = (unsigned char*)&number;
printf("%d\n",number);
if((number%2)==0)
charPointer[0]=charPointer[0] | 0x1;
//charPointer[0]=~charPointer[0];
else{
unsigned int complementNumber=~number;
number=(-1)*complementNumber;
}
printf("\n%d\n",number);
return 0;
}
</pre><pre title="CodeMonkey45223" input="yes">
</pre>
<pre lang="" line="1" title="CodeMonkey97417" class="run-this">The key is to find first zero and change the lower portion staring from that bit to 10....0. For example,
22 = 10110 -> 10111 = 23
23 = 10111 -> 11000 = 24
24 = 11000 -> 11001 = 25
25 = 11001 -> 11010 = 26
26 = 11010 -> 11011 = 27
public int minusOne(int n) {
int mask = 1;
int temp = ~n;
while ((mask & temp) == 0) {
mask |= mask << 1;
}
return mask ^ n;
}
</pre><pre title="CodeMonkey97417" input="yes">
</pre>
The method should be named as plusOne insttead of minusOne. Sorry for the misleading naming.
Alternatively, it can be implement as below:
"
public int plusOne(int n) {
int mask = 1;
int lowerSection = 1;
while ((mask & n) > 0) {
mask <<= 1;
lowerSection |= mask;
}
return n ^ lowerSection;
}
"
#include<stdio.h>
void main(){
int n;
printf("enter you no.");
scanf("%d",&n);
if(n%2==0)
n=n|1;
else
{
if((n&2)==0)
{
n=n>>1;
n=n|1;
n=n<<1;
}
else if((n&4)==0)
{
n=n>>2;
n=n|1;
n=n<<2;
}
else if((n&8)==0)
{
n=n>>3;
n=n|1;
n=n<<3;
}
else if((n&16)==0)
{
n=n>>4;
n=n|1;
n=n<<4;
}
else if((n&32)==0)
{
n=n>>5;
n=n|1;
n=n<<5;
}
else if((n&64)==0)
{
n=n>>6;
n=n|1;
n=n<<6;
}
else if((n&128)==0)
{
n=n>>7;
n=n|1;
n=n<<7;
}
else if((n&256)==0)
{
n=n>>8;
n=n|1;
n=n<<8;
}
}
printf("%d",n);
}
int inc(int n)
- xjshi July 01, 2011{
int i=1;
while(n&i)
{
n &= ~i;
i <<= 1;
}
return (n|i);
}