## Qualcomm Interview Question

int mask =0 ;

mask | = 1<<(n-1);

x= x&(~mask);

In the above solution, in place of "mask | = 1<<(n-1);" we can simply keep "mask = <<(n-1);". There is no need of using |=. Please correct me if I am wrong.

All of these solutions are of order n where n is the bit to be cleared. This can, however, be done in constant time with a lookup table. Build a table (an array) that has a preset bitmask for each bit in the integer. The 'Clear' function then looks up the mask using the value of n passed in. The mask is then applied and the modified value of x returned.

O(n) is too much for a function like this that may be used many times. The lookup table solution is O(1).

import java.lang.*;

import java.io.*;

import java util.*;

class toggle_n{

int n,b=1;

System.out.println("enter an number");

Scanner sc=new Scanner();

int a=sc.nextInt();

System.out.println("enter position to be toggle");

n=sc.nextInt();

b=b<<(n-1);

a=a^b;

System.out.println("number after toggling nth bit");

System.out.println(a);

}

```
//question 5 of java queston is to toggle nth bit
import java.io.*;
import java.util.*;
import java.math.*;
class toggle{
public int i,j;
int index=0,id=0;
int binary[],binary2[];
void toggling_nbit()throws IOException
{
System.out.println("ENTER A NUMBER ");
String s;
String p=" ";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
s=br.readLine();
int a=Integer.parseInt(s);
binary = new int[40];
tobinary(a);
System.out.println( );
System.out.println("WHICH BIT U WANT TO TOGGLE");
s=br.readLine( );
int n=Integer.parseInt(s);
int b=1;
int c=0;
System.out.println( );
for(i=1;i<=n-1;i++)
{ System.out.println( );
System.out.println("SHIFT FACTOR" );
System.out.println(c=(b<<i));
}
binary2=new int[40];
id = 0;
while(c> 0)
{
binary2[id++] = c%2;
c = c/2;
}
/*for( i = id-1;i >= 0;i--)
{
System.out.print(binary2[i]);
}*/
System.out.println( );
xor(binary,binary2);
}//toggling function closed
void tobinary(int a)
{
while(a > 0)
{
binary[index++]= a%2;
a=a/2;
}
System.out.println(" BINARY VALUE OF INPUT" );
for( i = index-1;i >= 0;i--)
{
System.out.print(binary[i]);
}
}//to binary function vclosed
void xor(int binary[],int binary2[])
{
System.out.println("VALUE AFTER TOGGLE");
for(i=0;i<=index-1;i++)
{
if(binary[i]==binary2[i])
{binary[i]=0;}
else
{ binary[i]=1;}
}
for( i = index-1;i >= 0;i--){ //binary of input
System.out.print(binary[i]);
}
}
}//class closed
class toggle_n{
public static void main(String args[]) throws IOException{
toggle t =new toggle( );
t.toggling_nbit( );
}//main closed
}//class closed
```

clear(int x,int n)

- Anonymous April 23, 2010{

int k=1;

int mask=0;

mask=k<<(n-1);

x=x & (~mask);

return x;

}