From 4bd411139935c8147e20f82d4154ec25c85ab3bf Mon Sep 17 00:00:00 2001 From: Richard Qin Date: Mon, 21 Sep 2026 00:45:05 +0800 Subject: leftBitCount --- bits.c | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/bits.c b/bits.c index 8297011..c5c08fa 100644 --- a/bits.c +++ b/bits.c @@ -155,7 +155,29 @@ int logicalShift(int x, int n) { * Difficulty: 4 */ int leftBitCount(int x) { - return 2; + int shift = 16; + int t = !((((x >> shift) & 0xFFFF) ^ 0xFFFF)); + int count = t << 4; + + shift = 24 + ~count + 1; + t = !((((x >> shift) & 0xFF) ^ 0xFF)); + count = count + (t << 3); + + shift = 28 + ~count + 1; + t = !((((x >> shift) & 0xF) ^ 0xF)); + count = count + (t << 2); + + shift = 30 + ~count + 1; + t = !((((x >> shift) & 0x3) ^ 0x3)); + count = count + (t << 1); + + shift = 31 + ~count + 1; + t = !((((x >> shift) & 0x1) ^ 0x1)); + count = count + t; + + count = count + !(~x); + + return count; } /* -- cgit v1.2.3