Apple Interview Question
967 Interview Reviews |
Back to all Apple Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer at Apple:
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (8)
1 of 1 people found this helpful
every number when AND'ed with number - 1 it would eliminate one binary number.\
count = 0;
while(n) {
n &= (n-1);
count++;
}
Helpful Answer?
Yes |
No
Inappropriate?
1. Convert the number into bits (we assume that all our bits of size 8)
2. "And" it with 1
3. check if the bit returned is 1 or now. if it is '1' increase some counter.
4. right shift 8 times and perform go to 2
look at the number 11:
counter=0;
0x000B, look at the last byte B: 1011
and that with 1, you get 1
counter now equals 1, right shift 8 times and get 0x0000
and with 1, get 0, doesn't increment counter.
so the number of 1's in 11 is 1.
Helpful Answer?
Yes |
No
Inappropriate?
0 of 1 people found this helpful
or you can do the following using properties of number.
every number when AND'ed with number - 1 it would eliminate one binary number.\
count = 0;
while(n) {
n &= (n-1);
count++;
}
Look at n=7, which we know has no 1's in it.
7 in binary: 0111
6 in binary: 0110
n=7&6;
so n=6;
counter=1;
loop again:
5 in binary=0101;
n=6&5=0110&0101=0100=4;
counter=2;
We can already see this is wrong answer should be 0;
Helpful Answer?
Yes |
No
Inappropriate?
3 of 3 people found this helpful
For finding out the number of ones in an integer, I would propose the following.
int NumberOfOnes(double number)
{
int counter = 0;
if (number == 0) return 0;
if (number == 1) return 1;
do
{
if (number % 10 == 1) counter++;
number = number / 10;
}
while (number);
return counter;
}
Helpful Answer?
Yes |
No
Inappropriate?
1 of 1 people found this helpful
def findBinOnes(integer):
val = integer
ones = 0
while val > 0:
if val & 1 == 1:
ones +=1
val = val >> 1
return ones
Decimal ones in python:
def findDecOnes(integer):
val = integer
ones = 0
while val > 0:
if val % 10 == 1:
ones += 1
val = val / 10
return ones
Helpful Answer?
Yes |
No
Inappropriate?
1 of 1 people found this helpful
#!/usr/bin/env ruby
123456718791.to_s.scan(/1/).size
Helpful Answer?
Yes |
No
Inappropriate?
int num = 0;
String str = Integer.toString ( n );
for(int i = 0 ; i < str.length() ; i++ ) {
if ( str.charAt ( i ) == '1' )
num++;
}
return num;
}
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up
0 of 0 people found this helpful
by jinggle:
2. "And" it with 1
3. check if the bit returned is 1 or now. if it is '1' increase some counter.
4. right shift 8 times and perform go to 2