Amazon Interview Question
Developer Program Engineers@Ashish, I think you are trying to say n & (n-1)
8 = 1000
7 = 0111
& = 0000
Means if a number's all bits are 1, then doing the AND operation with previous number (number - 1) will result in zero.
No... since all bits in n are 1, adding 1 to it makes the sum a power of two. So I am correct in my code.
step1: negate the number (~q say number is q)
step 2: find xor of the two number(Q xor ~Q)
step 3: IF step2 result == Q all the every digit in binary is 1 else false
if ((n ^ 0xFFFFFFFF) == 0) {
printf("n has all 1's");
}
else
{
printf("n has some 0's");
}
i have 2 similar answers. the 1st one is
if((x^o) == 1){ //x is the supplied number
system.out.println("this number "+x+" has all 1's in its bin.representation");
}
the second one is:
if((x^1) == 0){ //x is the supplied number
system.out.println("this number "+x+" has all 1's in its bin.representation");
}
The above algorithms can be solved by following that on every right shift of the binary number it's & operation with 1 should not be 0 if 0 then return true else till the number is greater than 0 return true if not found
Implementation:
#include<bits/stdc++.h>
using namespace std;
int findsetbits(int n){
while(n > 0){
if(n&1 == 0)
return 0;
n = n>>1;
}
return 1;
}
int main(){
int t, n;
cin>>t;
while(t--){
cin>>n;
if(findsetbits(n) == 0)
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}
return 0;
}
@Anonymous1 dude,this will work for every possible number.
Before posting answers , or rather don't post answers,fool!!
n ^ n will not work. It will always give 0 as an answer for every value of n.
01010101 n
01010101 n
------------------
00000000 n^n
The truth table of Xor Gate is below
11 0
10 1
01 1
00 0
---------------------------
Please guys lets not argue or use foul language. We all are here to learn.
Adding 1 to all 1s will produce a perfect power of 2
- Ashish Kaila June 14, 2011=> n & (n+1) == 0