ProgrammingHardHCL · Tech Mahindra pattern
What is printed? (Check if a number is a power of two.)
What is printed? (Check if a number is a power of two.)
int isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
int main(void) {
printf("%d %d %d %d", isPowerOfTwo(16), isPowerOfTwo(18), isPowerOfTwo(1), isPowerOfTwo(0));
}- A. 1 1 1 0
- B. 0 0 1 1
- C. 1 0 0 0
- D. 1 0 1 0
Correct answer: D. 1 0 1 0
n & (n-1) clears the lowest set bit; the result is 0 only when n had exactly one set bit (a power of two). 16 (10000) & 15 (01111) = 0 -> true. 18 (10010) & 17 (10001) = 10000 != 0 -> false. 1 (1) & 0 (0) = 0 -> true (2^0). 0 fails the n>0 check -> false.
More C Programming questions
- What is printed? c int swaptrick(int a, int b) { a = a ^ b; b = a ^ b; a = a ^ b; printf("%d %d ", a, b); return a + b; } int main(void) {…
- What is printed? c #define SETBIT(x, n) ((x) | (1 << (n))) #define CLEARBIT(x, n) ((x) & ~(1 << (n))) #define TOGGLEBIT(x, n) ((x) ^ (1 <<…
- What is printed? c #define SQUARE(x) x x int main(void) { int a = 5; printf("%d", SQUARE(a + 1)); }
- What is printed? c #define TWICE(x) x + x printf("%d", 2 TWICE(3));
- What is printed? c #define LOG(msg) printf("[LOG] %sn", msg) #ifdef DEBUG #define TRACE(msg) LOG(msg) #else #define TRACE(msg) #endif int…
- What is printed? c #define CONCAT(a, b) a##b int xy = 42; printf("%d", CONCAT(x, y));