Here is a C language program. On a machine with 8 8-bit byte long longs, what is the answer?

Here is a C language program. On a twos-complement machine with 8 8-bit byte long longs, what is the answer?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <stdio.h>

int main(int argc, char** argv) {
    unsigned long long value = -1;
    int counter = 0;
    while(value) {
        ++counter;
        value &= value-1;
    }
    printf("%d\n",counter);
    return 0;
}

This can be done easily without actually running the program. I have had it presented to me on job interviews without a computer to run it on available. I did answer correctly.

This code was ran as-is in the Brilliant coding environment. It computed the correct answer.


The answer is 64.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Each time through the loop, the rightmost 1 bit is removed. there are 64 1 bits in a unsigned long of value -1 on such a machine. Q.E.D.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...