Adobe Interview Question
Software Engineer / DevelopersXOR is right. But there seems to be an ambiguity about definition of odd bits.
Do we count starting from left? right? Do we include the padded zeroes on the left?
Above solution assumes the length of bits used.
int ToggleOddBits(int input){
int x=2;
while(x != 0){
input ^= x;
x= x<<2;
}
return input;
}
Please revert back if you dont agree with the above function.
public static int flipAllOddBitsOfNumber( final int num){
// Convert the no into a binary String
int N = num;
String binary="";
while(N!=0){
binary = N%2 + binary ;
N/=2;
}
// Flip bits at odd position in binary String
char [] car = binary.toCharArray();
for(int i =1 ; i<car.length ;i+=2)
if (car[i]=='0' )
car[i] = '1';
else
car[i] = '0';
// Convert from binary to decimal
int result =0;
for(int i = car.length - 1 ; i>=0 ; --i){
int powerTwo=1;
for(int j = 1 ; j < car.length -i ;++j )
powerTwo*= 2;
result+= powerTwo* (car[i] - '0');
}
return result ;
}
The following program should work. Havent tested it though.
int main ()
{
int num;
cin >> num;
char num_char[33];
int i = 0;
itoa(num, num_char, 10);
while (num_char[i] != '\0')
{
if ( (i%2) != 0)
{
if (num_char[i] == '0')
num_char[i] = '1';
else
num_char[1] = '0';
}
i++;
}
num = atoi(num_char);
cout << num;
return 0;
}
OR with 10101010101..
- Anonymous July 31, 2009